BuffConfig = {
    MAX_SELL_PRICE: 15 * 1e4,
    MIN_PRICE: .01,
    PayMethod: {
        ALIPAY_BALANCE: 3,
        ALIPAY_PAGE: 4,
        EPAY_BALANCE: 1,
        EPAY_QUICK_PAY: 2,
        ALIPAY_PAGE: 4,
        WX_PAGE: 6,
        ALIPAY_PAGE_PCREDIT: 10
    },
    STEAM_TIMEOUT: 30 * 1e3,
    SteamAPP: {
        APPID_MAPS: {
            "-578080": "pubg_recycle",
            433850: "h1z1",
            570: "dota2",
            578080: "pubg",
            730: "csgo",
            440: "tf2",
            252490: "rust"
        },
        CONTEXTID_MAPS: {
            "-578080": "2",
            433850: "1",
            570: "2",
            578080: "2",
            730: "2",
            440: "2",
            252490: "2"
        },
        DEFAULT_GAME: "csgo"
    }
};
function i18n(a, b) {
    var c = i18nData.getValue(a);
    return c ? (b && Object.keys(b).map(function(a, d) {
        c = c.replace("{{" + a + "}}", b[a])
    }),
    c) : a
}
function toggleGallery(a) {
    var b = $(".tr_gallery").eq(a);
    "none" == b.css("display") ? (b.show(),
    $(".j_gallery_handler").eq(a).html(i18n("collapse"))) : (b.hide(),
    $(".j_gallery_handler").eq(a).html(i18n("expand")))
}
function cancelBubble(a) {
    var b = a || window.event;
    b.stopPropagation ? b.stopPropagation() : b.cancelBubble = !0
}
function setShopRecommend() {
    var a = $("#j_recommend .slider-handle").eq(0)
      , b = $("#j_recommend .slider-handle").eq(1)
      , c = $("#j_recommend .list_card ul").eq(0)
      , d = 0
      , e = 161
      , f = c.children().length;
    c.css({
        width: e * f
    }),
    f > 5 && b.addClass("clickable"),
    b.click(function() {
        $(this).hasClass("clickable") && (d++,
        c.animate({
            marginLeft: -e * d
        }, 400),
        a.addClass("clickable"),
        d + 5 >= f && $(this).removeClass("clickable"))
    }),
    a.click(function() {
        $(this).hasClass("clickable") && (d--,
        c.animate({
            marginLeft: -e * d
        }, 400),
        b.addClass("clickable"),
        d <= 0 && $(this).removeClass("clickable"))
    })
}
var I18N = function() {
    function a(a) {
        var b = document.cookie.match(new RegExp("(^| )" + a + "=([^;]+)"));
        if (b) {
            var c = "";
            try {
                c = decodeURIComponent(b[2])
            } catch (a) {}
            return c
        }
        return ""
    }
    var b = {
        zh: {},
        en: {}
    }
      , c = "zh"
      , d = function() {
        var b = a("Locale-Supported") || c;
        return "zh-Hans" == b ? "zh" : b
    };
    return {
        updateData: function(a, c) {
            for (key in c)
                b[a][key] = c[key]
        },
        getValue: function(a) {
            var e = d();
            return a in b[e] ? b[e][a] : a in b[c] ? b[c][a] : a
        }
    }
}
  , i18nData = new I18N;
i18nData.updateData("zh", {
    collapse: "收起",
    expand: "展开",
    last_7_days_sell_stats: "最近7天出售统计",
    delivery_rate: "发货成功率",
    delivery_time: "平均发货时间"
}),
i18nData.updateData("en", {
    collapse: "Collapse",
    expand: "Expand",
    last_7_days_sell_stats: "Last 7 days sell stats",
    delivery_rate: "Delivery rate",
    delivery_time: "Delivery time"
});
var Popup = {
    boxes: [],
    baseIndex: null,
    show: function(a) {
        $("body").append("<div class='cover'></div>"),
        this.boxes.push($("#" + a));
        var b = this.boxes.length
          , c = this.boxes[b - 1];
        this.baseIndex = this.baseIndex || parseInt(c.css("z-index")),
        $(".cover").eq(b - 1).show().css("z-index", this.baseIndex + 2 * b),
        c.show().css({
            "margin-left": -c.width() / 2,
            "margin-top": -c.height() / 2,
            "z-index": this.baseIndex + 2 * b + 1
        }),
        Buff.initSelect("#" + a + " .w-Select"),
        Buff.initSteper("#" + a + " .w-Steper"),
        Buff.pricePatten("#" + a + " .j_filter")
    },
    hide: function() {
        var a = this.boxes.length;
        a > 0 && (this.boxes[a - 1].hide(),
        $(".cover").eq(a - 1).remove(),
        this.boxes.pop())
    }
}
  , Buff = {
    _timer_Toast: null,
    setCompValue: function(a, b) {
        var c = $("#" + a);
        if (c.hasClass("w-Search"))
            c.find("input").val(b);
        else if (c.hasClass("w-Counter")) {
            var d = c.find("input");
            b.min && d.eq(0).val(b.min),
            b.max && d.eq(1).val(b.max)
        } else if (c.hasClass("w-Order"))
            c.attr("value", b).addClass("w-Order_" + b);
        else if (c.hasClass("h1z1-selType"))
            c.children(".w-SelType").each(function(a, c) {
                if ($(c).find("p").attr("value") == b)
                    return $(c).addClass("selected").attr("value", b),
                    !1;
                $(c).find("li").each(function(a, d) {
                    if ($(d).attr("value") == b)
                        return $(d).addClass("on"),
                        $(c).addClass("selected").attr("value", b),
                        !1
                })
            });
        else if (c.hasClass("w-Select-Multi")) {
            c.attr("value", b);
            var e, f = "h6,p";
            c.find(f).each(function(a, c) {
                if ($(c).is("p") ? $(c).remove("on") : $(c).parent().removeClass("on"),
                $(c).attr("value") == b)
                    return $(c).is("p") ? $(c).addClass("on") : $(c).parent().addClass("on"),
                    e = $(c),
                    !1
            }),
            c.find("h3").html(e.html())
        } else {
            c.attr("value", b);
            var e, f = "li";
            if ((c.hasClass("w-Tag") || c.hasClass("w-Switcher")) && (f = "span,div"),
            c.find(f).removeClass("on").each(function(a, c) {
                if ($(c).attr("value") == b)
                    return $(c).addClass("on"),
                    e = $(c),
                    !1
            }),
            c.hasClass("w-Select") || c.hasClass("w-SelHero")) {
                var g = e.attr("title") || e.html();
                c.find("h3").html(g)
            }
        }
    },
    message: function(a, b) {
        $("#j_Message").length <= 0 && $("body").append('<div id="j_Message">'),
        $Message = $("#j_Message");
        var c = 3e3
          , d = $('<div class="w-Message"><div class="w-Message-cont"></div><i class="w-Message-close">×</i></div>');
        b ? ("success" == b.type ? d.addClass("w-Message_success") : "warning" == b.type && d.addClass("w-Message_warning"),
        "string" == typeof b.delay ? d.find(".w-Message-close").show().on("click", function() {
            d.remove(),
            b.callback && b.callback()
        }) : ("number" == typeof b.delay && (c = b.delay),
        setTimeout(function() {
            d.remove(),
            b.callback && b.callback()
        }, c))) : setTimeout(function() {
            d.remove()
        }, c),
        d.find(".w-Message-cont").html(a),
        d.slideDown(100),
        $Message.prepend(d)
    },
    toast: function(a, b) {
        var c = $("#j_w-Toast")
          , d = this;
        c.length < 1 && (c = $('<div id="j_w-Toast"></div>'),
        $("body").append(c)),
        c.hide(),
        c.attr("class", b && b.type ? "w-Toast_" + b.type : ""),
        b && b.type && (a = '<i class="icon icon_' + b.type + '_mid"></i>' + a),
        a = "<p>" + a + "</p>",
        clearTimeout(d._timer_Toast),
        setTimeout(function() {
            c.html(a).show().css({
                "margin-left": -c.outerWidth() / 2,
                "margin-top": -c.outerHeight() / 2
            }),
            d._timer_Toast = setTimeout(function() {
                c.fadeOut(function() {
                    c.html("")
                })
            }, 2e3)
        }, 100)
    },
    initSelect: function(a) {
        $(a).each(function(a, b) {
            var c = $(this);
            if (0 != $(this).find("ul").width() && "inited" != c.attr("init")) {
                c.attr("init", "inited");
                var d = $(this).find("ul").width() + 6
                  , e = $(this).find("h3")
                  , f = $(this).find("li");
                d <= e.outerWidth() + 8 && (d = e.outerWidth() + 18),
                d < 100 && (d = 100),
                $(this).find("ul").width(d),
                $(this).width(d),
                f.width(d - 18).off().click(function() {
                    e.html($(this).html()),
                    f.removeClass("on"),
                    $(this).addClass("on");
                    var a = $(this).attr("value");
                    void 0 == a && (a = ""),
                    c.removeClass("on").attr("value", a),
                    c.trigger("change")
                }),
                setTimeout(function() {
                    c.css("visibility", "visible")
                }, 200);
                var g;
                $(this).off().mouseleave(function() {
                    g = setTimeout(function() {
                        c.removeClass("on")
                    }, 300)
                }).mouseenter(function() {
                    clearTimeout(g)
                }),
                e.off().click(function() {
                    c.toggleClass("on")
                }),
                $.trim(e.html()) || (e.html(f.eq(0).html()),
                c.removeClass("on").attr("value", f.eq(0).attr("value")),
                f.eq(0).addClass("on"))
            }
        })
    },
    initSelectMulti: function(a) {
        $(a).each(function(a, b) {
            var c = $(this);
            if (0 != $(this).find("ul").width() && "inited" != c.attr("init")) {
                c.attr("init", "inited");
                var d = $(this).find("ul").width() + 6
                  , e = $(this).find("h3")
                  , f = $(this).find("li");
                d <= e.outerWidth() + 8 && (d = e.outerWidth() + 18),
                $(this).find("ul").width(d),
                "left" === $(this).attr("data-postion") ? $(this).find("li div").css({
                    left: "auto",
                    right: d + 1
                }) : $(this).find("li div").css("left", d + 1),
                $(this).width(d);
                var g = $(this).attr("data-multi")
                  , h = $(this).attr("data-childSingle");
                g ? $(this).find("ul").eq(0).on("click", "h6,p", function() {
                    if ($(this).is("p")) {
                        $(this).hasClass("on") ? $(this).removeClass("on") : ($(this).addClass("on"),
                        h && $(this).siblings().removeClass("on"));
                        var a = c.find(".on")
                          , b = [];
                        $.each(a, function(c, d) {
                            var e = a.eq(c).attr("value");
                            e && b.push(e)
                        }),
                        c.attr("value", b.join(",")),
                        c.trigger("change")
                    }
                }) : $(this).find("ul").eq(0).on("click", "h6,p", function() {
                    if ($(this).attr("value") && "" != $(this).attr("value") || 0 == $(this).attr("value")) {
                        e.html($(this).html()),
                        c.removeClass("on").find("li,p").removeClass("on"),
                        $(this).is("p") ? $(this).addClass("on") : $(this).parent().addClass("on");
                        var a = $(this).attr("value");
                        void 0 == a && (a = ""),
                        c.removeClass("on").attr("value", a),
                        c.trigger("change")
                    }
                });
                var i = []
                  , j = [];
                f.mouseenter(function() {
                    var a = $(this)
                      , b = a.index();
                    clearTimeout(i[b]),
                    j[b] = setTimeout(function() {
                        var b = document.documentElement.clientHeight
                          , c = a.offset()
                          , d = a.find("div")
                          , e = d.height()
                          , f = "auto"
                          , g = "auto";
                        c.top + e > b ? g = c.top - b + 30 : f = 1,
                        a.find("div").css({
                            top: f,
                            bottom: g
                        }),
                        a.addClass("hover")
                    }, 200)
                }).mouseleave(function() {
                    var b = $(this);
                    a = b.index(),
                    clearTimeout(j[a]),
                    i[a] = setTimeout(function() {
                        b.removeClass("hover")
                    }, 200)
                }),
                setTimeout(function() {
                    c.css("visibility", "visible")
                }, 100);
                var k;
                $(this).off().mouseleave(function() {
                    k = setTimeout(function() {
                        c.removeClass("on")
                    }, 200)
                }).mouseenter(function() {
                    clearTimeout(k)
                }),
                e.off().click(function() {
                    c.toggleClass("on")
                }),
                $.trim(e.html()) || (e.html(f.eq(0).html()),
                c.removeClass("on").attr("value", f.eq(0).attr("value")),
                f.eq(0).addClass("on"))
            }
        })
    },
    initSteper: function(a) {
        $(a).each(function(a, b) {
            input_Timer = null;
            var c = $(this)
              , d = c.find("input").eq(0)
              , e = parseInt(c.attr("min"))
              , f = parseInt(c.attr("max"))
              , g = 1;
            c.attr("value") && !isNaN(parseInt(c.attr("value"))) && (g = parseInt(c.attr("value")));
            var h = g;
            c.attr("value", g),
            d.val(g),
            c.off().on("click", "span", function() {
                if (0 == $(this).index()) {
                    var a = g - 1;
                    (!e || a >= e) && (c.attr("value", a),
                    d.val(a),
                    g = a,
                    c.trigger("change"),
                    $(this).siblings().removeClass("disabled"),
                    a == e && $(this).addClass("disabled"))
                } else {
                    var a = g + 1;
                    (!f || a <= f) && (c.attr("value", a),
                    d.val(a),
                    g = a,
                    c.trigger("change"),
                    $(this).siblings().removeClass("disabled"),
                    a == f && $(this).addClass("disabled"))
                }
            }),
            d.off().on("keypress", function(a) {
                var b = a.keyCode || a.charCode;
                return 9 == b || 13 == b || 37 == b || 39 == b || /[\b\d\-]/.test(String.fromCharCode(b))
            }).on("keyup", function(a) {
                clearTimeout(input_Timer);
                var b = $.trim($(this).val());
                "" != b && "-" != b && (/[^0-9\.\-]/.test(b) && (b = b.replace(/[^0-9\.\-]/g, "")),
                b = parseInt(d.val()),
                b || (b = h),
                e && b <= e ? (b = e,
                c.find("span").eq(0).addClass("disabled"),
                c.find("span").eq(1).removeClass("disabled")) : e && b > e && c.find("span").eq(0).removeClass("disabled"),
                f && b >= f ? (b = f,
                c.find("span").eq(0).removeClass("disabled"),
                c.find("span").eq(1).addClass("disabled")) : f && b < f && c.find("span").eq(1).removeClass("disabled"),
                g = b,
                input_Timer = setTimeout(function() {
                    d.val(b),
                    c.attr("value", b),
                    c.trigger("change")
                }, 300))
            }).on("blur", function() {
                var a = $.trim($(this).val());
                "" != a && "-" != a || (a = h,
                g = a,
                d.val(a),
                c.attr("value", a),
                c.trigger("change"))
            })
        })
    },
    pricePatten: function(a) {
        var b = null;
        $(a).each(function() {
            $(this).attr("pattened") || $(this).bind("input", function(a) {
                var c = $(this).val()
                  , d = c.replace(/[^\d.]/g, "")
                  , e = d.indexOf(".");
                -1 !== e && (d = d.replace(/\./g, ""),
                d = d.slice(0, e) + "." + d.slice(e, e + 2));
                var f = d.split(".")[0]
                  , g = d.split(".")[1]
                  , h = "";
                f ? (f = parseInt(f, 10).toString(10),
                h = f + (void 0 !== g ? "." + g : "")) : void 0 === g && "." !== d || (h = "0." + g),
                c !== h && $(this).val(h);
                var i = $(this);
                clearTimeout(b),
                b = setTimeout(function() {
                    i.trigger("format", h)
                }, 600)
            }).attr("pattened", !0)
        })
    },
    getSelection: function() {
        var a = "";
        if (window.getSelection)
            if (!document.activeElement || "textarea" != document.activeElement.tagName.toLowerCase() && "input" != document.activeElement.tagName.toLowerCase()) {
                var b = window.getSelection();
                a = b.toString()
            } else {
                var c = document.activeElement.value;
                a = c.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd)
            }
        else if (document.selection.createRange) {
            var d = document.selection.createRange();
            a = d.text
        }
        return a
    },
    initSelectSearch: function(a) {
        var b = "on";
        $(document.body).on("mouseleave", a, function(a) {
            var c = $(this);
            setTimeout(function() {
                c.removeClass(b)
            }, 200)
        }).on("click", a + " li", function(b) {
            var c = $(this);
            if (!c.hasClass("none")) {
                var d = $(c.parents(a))
                  , e = d.attr("value")
                  , f = d.attr("title")
                  , g = c.attr("value")
                  , h = c.attr("title");
                d.mouseleave(),
                e === g && f === h || (d.find("h3").html(g ? c.html() : c.text()),
                d.attr("value", g).attr("title", h).trigger("change"))
            }
        }).on("click", a + " h3", function(c) {
            var d = $(this)
              , e = $(d.parents(a));
            e.hasClass("w-Selectsearch--disable") || (e.hasClass(b) ? e.removeClass(b) : (e.addClass(b),
            e.find("input").focus(),
            e.trigger("init")))
        })
    },
    initSelectBtn: function(a) {
        $(document.body).on("mouseenter", a + " .w-SelectBtn-arr", function(a) {
            var b = $(this)
              , c = b.siblings(".w-SelectBtn_options");
            c.show();
            var d = null;
            return b.off().on("mouseleave", function() {
                d = setTimeout(function() {
                    c.hide()
                }, 200)
            }),
            c.on("mouseenter", function() {
                clearTimeout(d),
                c.show()
            }).on("mouseleave", function() {
                clearTimeout(d),
                c.hide()
            }),
            c.on("click", "li", function() {
                clearTimeout(d),
                c.hide()
            }),
            !1
        })
    },
    initCouponSelect: function(a, b, c) {
        if (!($("#" + a).length < 0)) {
            var d = $("#" + a);
            d.off();
            var e = "";
            if (!b.options || 0 == b.options.length)
                return b.placeholder = i18n("no_coupon_to_use"),
                d.css("cursor", "text"),
                void d.html(i18n("no_coupon_to_use"));
            var f = [];
            if ($.each(b.options, function(a, b) {
                b.desc = b.desc || "",
                f.push('<li data-value="' + b.value + '"><span>' + b.label + "</span><small>" + b.desc + "</small></li>")
            }),
            e = "<ul>" + f.join("") + "</ul>",
            d.on("mouseenter", function() {
                clearTimeout(window["couponTimmer" + a]),
                $(this).addClass("on")
            }).on("mouseleave", function() {
                var b = this;
                window["couponTimmer" + a] = setTimeout(function() {
                    $(b).removeClass("on")
                }, 500)
            }).on("click", "li", function(e) {
                var f = $(this);
                d.removeClass("on"),
                c ? c($(this).attr("data-value"), a).then(function() {
                    d.find("h3 span").html(f.find("span").html()),
                    d.find("li").removeClass("on"),
                    d.attr("data-value", f.attr("data-value")),
                    f.addClass("on"),
                    "false" == f.attr("data-value") ? d.removeClass("setted").find("h3 span").html(b.placeholder) : d.addClass("setted"),
                    d.trigger("change")
                }, function() {}) : (d.find("h3 span").html(f.find("span").html()),
                d.find("li").removeClass("on"),
                d.attr("data-value", f.attr("data-value")),
                f.addClass("on"),
                "false" == f.attr("data-value") ? d.removeClass("setted").find("h3 span").html(i18n("please_choose_coupon")) : d.addClass("setted"),
                d.trigger("change"))
            }),
            d.html("<h3><span>" + b.placeholder + '</span><i class="icon icon_arr_light_down"></i></h3>' + e),
            "defaultIndex"in b && -1 != b.defaultIndex) {
                var g = d.find("li").eq(b.defaultIndex);
                d.find("h3 span").html(g.find("span").html()),
                d.find("li").removeClass("on"),
                d.attr("data-value", g.attr("data-value")),
                g.addClass("on"),
                "false" == g.attr("data-value") ? d.removeClass("setted").find("h3 span").html(i18n("please_choose_coupon")) : d.addClass("setted")
            }
        }
    },
    initTextArea: function(a) {
        $(document.body).on("input", a + " textarea", function(a) {
            var b = $(this)
              , c = b.val()
              , d = c.length
              , e = b.attr("maxlength")
              , f = b.parent().find(".w-TextArea-num").eq(0);
            f && (f.html(d + ""),
            e && d >= e ? f.css("color", "#D10D1C") : d > 0 ? f.css("color", "#3E3E3E") : f.css("color", ""))
        })
    }
};
$(function() {
    function initSelHero(a) {
        a.toggleClass("on").off(),
        a.on("click", "li", function() {
            a.find("li").removeClass("on"),
            $(this).addClass("on"),
            a.removeClass("on"),
            a.find("h3").html($(this).attr("title")),
            a.attr("value", $(this).attr("value")),
            a.trigger("change")
        }).on("mouseleave", function() {
            timerSelHero = setTimeout(function() {
                a.removeClass("on")
            }, 300)
        }).on("mouseenter", function() {
            clearTimeout(timerSelHero)
        })
    }
    function initStone(a) {
        a.toggleClass("on").off(),
        a.on("click", "li", function() {
            a.find("li").removeClass("on"),
            $(this).addClass("on"),
            a.removeClass("on"),
            a.find("h3").html($(this).attr("title")),
            a.attr("value", $(this).attr("value")),
            a.trigger("change")
        }).on("mouseleave", function() {
            timerStone = setTimeout(function() {
                a.removeClass("on")
            }, 300)
        }).on("mouseenter", function() {
            clearTimeout(timerStone)
        }).on("click", "h5", function() {
            var b = $(this).index();
            $(this).addClass("on").siblings().removeClass("on"),
            a.find(".stone-list").hide().eq(b).show()
        })
    }
    /msie/.test(navigator.userAgent.toLowerCase()) && $("input[placeholder],textarea[placeholder],div[placeholder]").each(function(a, b) {
        var c = $(b).attr("placeholder");
        "" == $.trim($(b).val()) && $(b).addClass("c_placeholder").val(c),
        $(this).focus(function() {
            $.trim($(b).val()) == c && $(b).removeClass("c_placeholder").val("")
        }).blur(function() {
            "" != $.trim($(b).val()) && $.trim($(b).val()) != c || $(b).addClass("c_placeholder").val(c)
        })
    }),
    $("div[placeholder]").each(function(a, b) {
        var c = $(b).attr("placeholder");
        "" == $.trim($(b).html()) && $(b).addClass("c_placeholder").html(c),
        $(this).focus(function() {
            $.trim($(b).html()) == c && $(b).removeClass("c_placeholder").html("")
        }).blur(function() {
            "" != $.trim($(b).html()) && $.trim($(b).html()) != c && "<br>" != $.trim($(b).html()) || $(b).addClass("c_placeholder").html(c)
        })
    }),
    Buff.initSelect(".w-Select"),
    Buff.initSelectMulti(".w-Select-Multi"),
    Buff.initSteper(".w-Steper"),
    Buff.initSelectSearch(".w-Selectsearch"),
    Buff.initSelectBtn(".w-SelectBtn"),
    Buff.initTextArea(".w-TextArea"),
    $("#j_gamesel").on("mouseenter", function() {
        $(this).addClass("on")
    }).on("mouseleave", function() {
        $(this).removeClass("on")
    }).on("click", "div p", function() {
        $("#j_gamesel").removeClass("on").trigger("change", $(this).index()).find("h4").html($(this).html())
    }),
    $(".j_drop-handler").on("mouseenter", function() {
        $(this).addClass("showdrop")
    }).on("mouseleave", function() {
        $(this).removeClass("showdrop")
    }),
    $("body").on("click", ".w-SelHero h3", function() {
        initSelHero($(this).parent())
    }),
    $("body").on("click", ".w-Stone h3", function() {
        initStone($(this).parent())
    }),
    $("body").on("click", ".w-Switcher span", function() {
        $(this).hasClass("on") || ($(this).addClass("on").siblings().removeClass("on"),
        $(this).parent().attr("value", $(this).attr("value")),
        $(this).parent().trigger("change"))
    }),
    $("body").on("click", ".w-Order,.tb-Order", function() {
        var a = $(this).attr("value");
        a && "null" != a && "asc" != a ? "des" == a && $(this).attr({
            value: "asc"
        }).removeClass("w-Order_des").addClass("w-Order_asc") : $(this).attr({
            value: "des"
        }).removeClass("w-Order_asc").addClass("w-Order_des"),
        $(this).trigger("change")
    }),
    $("body").on("click", ".w-Tag span,.w-Tag div", function() {
        $(this).toggleClass("on").siblings().removeClass("on");
        var a = $(this).hasClass("on") ? $(this).attr("value") : "";
        $(this).parent().attr("value", a).trigger("change")
    }),
    $(".w-Counter").hover(function() {
        $(this).find(".w-Counter-pannel").show()
    }, function() {
        $(this).find(".w-Counter-pannel").hide()
    }).on("click", ".i_Btn_sub", function() {
        $(this).parent().parent().find(".i_Text").val("")
    }).on("click", ".i_Btn_main", function() {
        var a = $(this).parent().parent();
        a.find(".w-Counter-pannel").hide();
        var b = $.trim(a.find(".i_Text").eq(0).val()) || null
          , c = $.trim(a.find(".i_Text").eq(1).val()) || null;
        a.attr("value", b + "," + c).trigger("change")
    }),
    $("body").on("click", ".w-Checkbox span", function() {
        var a;
        $(this).index();
        if (a = $(this).parent().attr("value") && "" != $.trim($(this).parent().attr("value")) ? $(this).parent().attr("value").split(",") : new Array,
        $(this).hasClass("on")) {
            $(this).removeClass("on");
            var b = $(this).attr("value");
            $.each(a, function(c, d) {
                if (b == d)
                    return a.splice(c, 1),
                    !1
            }),
            $(this).parent().attr("value", a.toString())
        } else
            $(this).addClass("on"),
            a.push($(this).attr("value")),
            $(this).parent().attr("value", a.toString());
        $(this).parent().trigger("change")
    }),
    $("body").on("click", ".w-Checkbox span a", function(a) {
        a.stopPropagation()
    }),
    $("body").on("click", ".w-Radio span", function() {
        $(this).hasClass("on") || ($(this).addClass("on").siblings().removeClass("on"),
        $(this).parent().attr("value", $(this).attr("value")).trigger("change"))
    }),
    $(".w-Sel-Hero .hero-type").hover(function() {
        $(this).addClass("on")
    }, function() {
        $(this).removeClass("on")
    }).on("click", "li", function() {
        var a = $(this).parent().parent();
        $(this).hasClass("on") ? ($(this).removeClass("on"),
        a.parent().attr("value", "")) : (a.parent().attr("value", $(this).attr("value")).find("li").removeClass("on"),
        $(this).addClass("on")),
        a.parent().trigger("change")
    }),
    $(".w-SelType").hover(function() {
        $(this).addClass("on")
    }, function() {
        $(this).removeClass("on")
    }).on("click", "li", function(a) {
        var b = $(this).parent().parent();
        $(this).hasClass("on") ? ($(this).removeClass("on"),
        b.attr("value", ""),
        b.removeClass("selected")) : (b.attr("value", $(this).attr("value")).find("li").removeClass("on"),
        $(this).addClass("on"),
        b.addClass("selected"),
        b.parent().hasClass("h1z1-selType") && b.siblings(".selected").eq(0).removeClass("selected").attr("value", "").find(".on").removeClass("on")),
        a.stopPropagation(),
        b.trigger("change")
    }),
    $(".h1z1-selType").on("click", ".w-SelType", function() {
        $(this).hasClass("selected") && $(this).attr("value") == $(this).find("p").attr("value") ? $(this).attr("value", "").removeClass("selected").find(".on").removeClass("on") : ($(this).attr("value", $(this).find("p").attr("value")).addClass("selected").siblings(".selected").eq(0).removeClass("selected").attr("value", "").find(".on").removeClass("on"),
        $(this).find(".on").removeClass("on")),
        $(this).trigger("change")
    }),
    $("body").on("click", ".w-OrderGroup .w-Order", function(a, b) {
        $(this).siblings().attr({
            class: "w-Order",
            value: ""
        })
    });
    var tipsHandlerTimer = null;
    $("body").on("mouseenter", ".j_tips_handler", function(index, item) {
        if (clearTimeout(tipsHandlerTimer),
        $(this).attr("precalculate") && eval($(this).attr("precalculate")),
        $(this).attr("data-title") || $(this).attr("data-content")) {
            var $tip = $("#j_fixedtip");
            $tip.length <= 0 && ($tip = $('<div class="fixedtip" id="j_fixedtip"> <i class="icon icon_arr_big_right"></i> <h3></h3> <div></div> </div>'),
            $("body").append($tip)),
            $(this).attr("data-width") && $tip.css("width", $(this).attr("data-width")),
            $tip.find("h3").html($(this).attr("data-title")),
            $tip.find("div").html($(this).attr("data-content"));
            var left = $(this).offset().left
              , top = $(this).offset().top
              , direction = $(this).attr("data-direction");
            switch ($tip.attr("style", ""),
            $tip.removeClass("fixedtip2"),
            direction) {
            case "right":
                $tip.find(".icon").attr("class", "icon icon_arr_big_left"),
                $tip.css({
                    left: left + $(this).width() + 16,
                    top: top,
                    marginTop: -.5 * ($tip.height() + 10)
                }).show();
                break;
            case "bottom":
                $tip.addClass("fixedtip2"),
                $tip.find(".icon").attr("class", "icon icon_arr_big_left icon_arr_big_bot"),
                $tip.css({
                    left: left + $(this).width() / 2 - $tip.width() / 2 - 8,
                    top: top + $(this).height() + 10
                }).show();
                break;
            case "top":
                $tip.addClass("fixedtip2"),
                $tip.find(".icon").attr("class", "icon icon_arr_big_left icon_arr_big_top"),
                $tip.css({
                    left: left + $(this).width() / 2 - $tip.width() / 2 - 8,
                    top: top - $tip.height() - $(this).height() + 5
                }).show();
                break;
            default:
                $tip.find(".icon").attr("class", "icon  icon_arr_big_right"),
                $tip.css({
                    left: left,
                    top: top,
                    marginLeft: -1 * ($tip.width() + 40),
                    marginTop: -.5 * ($tip.height() + 10)
                }).show()
            }
        }
        return !1
    }).on("mouseleave", ".j_tips_handler", function() {
        return tipsHandlerTimer = setTimeout(function() {
            $("#j_fixedtip").hide()
        }, 150),
        !1
    }).on("mouseenter", "#j_fixedtip", function() {
        return clearTimeout(tipsHandlerTimer),
        !1
    }).on("mouseleave", "#j_fixedtip", function() {
        return tipsHandlerTimer = setTimeout(function() {
            $("#j_fixedtip").hide()
        }, 150),
        !1
    }),
    $("body").on("mouseenter", ".j_rolluutips_handler", function(a, b) {
        var c = $("#j_rolluutip");
        c.length <= 0 && (c = $('<div class="rolluutip" id="j_rolluutip"><img src="' + $(this).attr("data-img") + '"></div>'),
        $("body").append(c));
        var d = $(this).offset().left
          , e = $(this).offset().top
          , f = ""
          , g = "absolute";
        $.each($(this).parents(), function(a, b) {
            if ($(b).hasClass("popup"))
                return g = "fixed",
                "auto" !== e && (e -= $(window).scrollTop()),
                !1
        }),
        e + c.width() > $(window).height() ? (e = "auto",
        f = 10) : e -= 22,
        c.find(".icon").attr("class", "icon icon_arr_big_left"),
        c.css({
            left: d + $(this).width() + 10,
            top: e,
            bottom: f,
            position: g
        }).show()
    }).on("mouseleave", ".j_rolluutips_handler", function() {
        $("#j_rolluutip").hide()
    }),
    $("body").on("mouseenter", ".j_shoptip_handler", function(a, b) {
        if ($(this).attr("data-shop")) {
            var c = $("#j_fixedtip_shop");
            c.length <= 0 && (c = $('<div class="fixedtip fixedtip_shop" id="j_fixedtip_shop"> <i class="icon icon_arr_big_left"></i><h2>' + i18n("last_7_days_sell_stats") + '</h2><div class="line"></div><ul></ul></div>'),
            $("body").append(c));
            var d = $(this).attr("data-shop").split("|")
              , e = "-&nbsp;"
              , f = "-&nbsp;";
            d[0] && (e = '<strong class="c_Blue">' + d[0] + "</strong>%"),
            d[1] && (d[1] <= 60 ? f = '<strong class="c_Blue">' + d[1] + "</strong>" + i18n("minutes") : (f = '<strong class="c_Blue">' + Math.floor(d[1] / 60) + "</strong>" + i18n("hours"),
            d[1] % 60 > 0 && (f += '<strong class="c_Blue">' + d[1] % 60 + "</strong>" + i18n("minute"))));
            var g = "<li><label>" + i18n("delivery_rate") + "</label><span>" + e + "</span></li><li><label>" + i18n("delivery_time") + "</label><span>" + f + "</span></li>";
            c.find("ul").html(g);
            var h = $(this).offset().left
              , i = $(this).offset().top;
            c.css({
                left: h + $(this).width() + 16,
                top: i,
                marginTop: -.5 * (c.height() + 10)
            }).show()
        }
    }).on("mouseleave", ".j_shoptip_handler", function() {
        $("#j_fixedtip_shop").hide()
    });
    var ua = window.navigator.userAgent.toLowerCase();
    "ipad" != ua.match(/ipad/i) && "iphone" != ua.match(/iphone/i) || $("body div").on("click", function() {}),
    $("body").on("click", ".with-gallery", function(a) {
        toggleGallery($(".with-gallery").index(this))
    }),
    $("body").on("click", ".j_gallery_handler", function(a) {
        toggleGallery($(".j_gallery_handler").index(this))
    }),
    $.ajax({
        url: "https://websource.nie.netease.com/copyright/get/byreferer",
        type: "GET",
        dataType: "jsonp",
        success: function(a) {
            a && a.success && a.result.copyright && (a.result.copyright = a.result.copyright.replace("netease.1", "netease.2").replace("nie.1", "nie.2"),
            $("#NIE-copyRight").html(a.result.copyright))
        },
        error: function() {}
    });
    var $qqGroup = $("#j_bar-qq-list")
      , $qqGroups = $("#j_bar-qq-list li")
      , $qqGroupNav = $("#j_bar-qq-nav")
      , $qqGroupId = $("#j_qq-group-number")
      , $qqGroupName = $("#j_qq-group-name");
    $qqGroupId.html($qqGroups.eq(0).attr("data-group-id")),
    $qqGroupName.html($qqGroups.eq(0).attr("data-group-name")),
    $qqGroups.length > 1 && ($qqGroups.each(function(a, b) {
        $qqGroupNav.append("<span></span>")
    }),
    $qqGroupNav.find("span").eq(0).addClass("on"),
    $qqGroup.width(160 * $qqGroups.length),
    $qqGroupNav.on("click", "span", function(a) {
        var b = $("#j_bar-qq-nav span").index(this);
        $(this).addClass("on").siblings().removeClass("on"),
        $qqGroupId.html($qqGroups.eq(b).attr("data-group-id")),
        $qqGroupName.html($qqGroups.eq(b).attr("data-group-name")),
        $qqGroup.animate({
            marginLeft: -160 * b
        }, "fast")
    })),
    qqGroupTimer = null,
    $("#j_qq-gruop-handler").mouseenter(function() {
        clearTimeout(qqGroupTimer),
        $("#j_qq-group").show()
    }).mouseleave(function() {
        qqGroupTimer = setTimeout(function() {
            $("#j_qq-group").hide()
        }, 300)
    }),
    $("#j_qq-group").hover(function() {
        clearTimeout(qqGroupTimer)
    }, function() {
        qqGroupTimer = setTimeout(function() {
            $("#j_qq-group").hide()
        }, 300)
    })
});
buffPlugin = function() {
    var init_alert = function() {
        Buff.alert = function(config) {
            var title = config.title || i18n("prompt");
            var type = config.type;
            var message = config.message || "";
            var hideCancel = config.hideCancel || false;
            var hideClose = config.hideClose || false;
            var hideConfirm = config.hideConfirm || false;
            var cancelText = config.cancelText || i18n("cancel");
            var confirmText = config.confirmText || i18n("ok");
            var onClose = config.onClose;
            var error = config.error || false;
            var success = config.success;
            var cancel = config.cancel;
            var hide_popup_after_success = config.hide_popup_after_success;
            var hide_popup_after_cancel = config.hide_popup_after_cancel;
            var width = config.width;
            var rememberDismiss = config.rememberDismiss;
            var extraClasses = config.extraClasses || "";
            var popup_id = randomstring(10);
            if (rememberDismiss) {
                if (localStorage.getItem("remember_dismiss_" + rememberDismiss)) {
                    if (success) {
                        success(true);
                        return
                    }
                }
            }
            var style = "";
            if (width) {
                style += "width:" + width + "px; margin-left:-" + (width / 2).toFixed(0) + "px;"
            }
            var html = '<div class="popup popup_common ' + extraClasses + '" id="' + popup_id + '" style="' + style + '">';
            if (!hideClose)
                html += '<a class="popup-close" href="javascript:;">×</a>';
            if (type == "success") {
                html += '<div class="popup-cont popup_success">'
            } else if (type == "error") {
                html += '<div class="popup-cont popup_error">'
            } else {
                html += '<div class="popup-cont">'
            }
            if (title)
                html += "<h2>" + title + "</h2>";
            if (message)
                html += '<div class="popup-desc"><p>' + message + "</p></div>";
            html += "</div>";
            html += '<div class="popup-btns">';
            if (rememberDismiss) {
                html += '<div class="w-Checkbox" id="remember-' + popup_id + '"><span value="1"><i class="icon icon_checkbox"></i>' + i18n("no_longer_prompt") + "</span></div><br><br>"
            }
            if (!hideCancel)
                html += '<a href="#" class="i_Btn i_Btn_sub">' + cancelText + "</a>";
            if (!hideConfirm)
                html += '<a href="#" class="i_Btn i_Btn_main">' + confirmText + "</a>";
            html += "</div>";
            html += "</div>";
            $("body").append(html);
            $("#" + popup_id + " .i_Btn_sub").click(function(e) {
                e.preventDefault();
                if (typeof cancel != "undefined") {
                    cancel()
                }
                if (hide_popup_after_cancel || typeof hide_popup_after_cancel == "undefined")
                    Popup.hide()
            });
            $("#" + popup_id + " .popup-close").click(function(e) {
                e.preventDefault();
                Popup.hide();
                if (typeof onClose != "undefined") {
                    onClose()
                }
            });
            $("#" + popup_id + " .i_Btn_main").click(function(e) {
                e.preventDefault();
                if ($("#remember-" + popup_id).attr("value") === "1") {
                    localStorage.setItem("remember_dismiss_" + rememberDismiss, "1")
                }
                if (hide_popup_after_success || typeof hide_popup_after_success == "undefined")
                    Popup.hide();
                if (typeof success != "undefined") {
                    success()
                }
            });
            Popup.show(popup_id);
            return popup_id
        }
    };
    var init_guide = function() {
        Buff.guide = function(config) {
            var title = config.title || i18n("description");
            var hideClose = config.hideClose || false;
            var confirmText = config.confirmText || i18n("ok");
            var onConfirm = config.onConfirm;
            var rememberDismiss = config.rememberDismiss;
            var content = config.content || "";
            var popup_id = randomstring(10);
            if (rememberDismiss) {
                if (localStorage.getItem("remember_dismiss_" + rememberDismiss)) {
                    if (typeof onConfirm != "undefined") {
                        onConfirm()
                    }
                    return
                }
            }
            var html = '<div class="popup popup_guide_sell" id="' + popup_id + '" style="width:600px;">';
            if (!hideClose) {
                html += '<a class="popup-close" href="javascript:;" onclick="Popup.hide()">×</a>'
            }
            html += '<div class="popup-header"><h2>' + title + '</h2></div>                            <div class="popup-cont">' + content + '<div class="popup-btns">';
            if (rememberDismiss) {
                html += '<div class="w-Checkbox f_14px" name="remember" value="">                                        <span value="1"><i class="icon icon_checkbox"></i>' + i18n("no_longer_prompt") + "</span>                                    </div>"
            }
            html += '<a href="javascript:;" class="i_Btn i_Btn_main">' + confirmText + "</a>                                </div>                            </div>                        </div>";
            $("body").append(html);
            $("#" + popup_id + " .i_Btn_main").click(function(e) {
                e.preventDefault();
                if ($("#" + popup_id + ' .w-Checkbox[name="remember"]').attr("value") === "1") {
                    localStorage.setItem("remember_dismiss_" + rememberDismiss, "1")
                }
                if (typeof onConfirm != "undefined") {
                    onConfirm()
                }
                Popup.hide()
            });
            Popup.show(popup_id)
        }
    };
    var init_dialog = function() {
        Buff.dialog = function(config) {
            var title = config.title || i18n("description");
            var hideClose = config.hideClose || false;
            var cancelText = config.cancelText || i18n("cancel");
            var confirmText = config.confirmText || i18n("ok");
            var onConfirm = config.onConfirm;
            var content = config.content || "";
            var popup_id = randomstring(10);
            var html = '<div class="popup_cover" id="popup_cover_' + popup_id + '" style="z-index:600"><div class="popup popup_guide_sell" id="' + popup_id + '" style="width:600px;">';
            if (!hideClose) {
                html += '<a class="popup-close" href="javascript:;">×</a>'
            }
            html += '<div class="popup-header"><h2>' + title + '</h2></div>                            <div class="popup-cont">' + content + '<div class="popup-btns">';
            html += '<a href="javascript:;" class="i_Btn i_Btn_sub">' + cancelText + '</a>                                    <a href="javascript:;" class="i_Btn i_Btn_main">' + confirmText + "</a>                                </div>                            </div>                        </div>";
            $("body").append(html);
            var popup = $("#" + popup_id);
            $("#" + popup_id + " .popup-close").click(function(e) {
                Popup.hide();
                popup.remove()
            });
            $("#" + popup_id + " .i_Btn_sub").click(function(e) {
                Popup.hide();
                popup.remove()
            });
            $("#" + popup_id + " .i_Btn_main").click(function(e) {
                if (typeof onConfirm != "undefined") {
                    onConfirm(popup)
                } else {
                    popup.remove()
                }
            });
            Popup.show(popup_id)
        }
    };
    var init = function() {
        init_alert();
        init_guide();
        init_dialog()
    };
    return {
        init: init
    }
}();
selectSearch = function(options) {
    this.bind = function() {
        var binded = $(this.selector).attr("bind");
        if (binded) {
            return
        }
        var timer = null
          , self = this;
        $(this.selector + " .w-Search input").on("keyup", function(e) {
            var $el = $(this)
              , value = $el.val();
            value = $.trim(value);
            if (value && value === self.val) {
                return false
            }
            clearTimeout(timer);
            timer = setTimeout(function() {
                self.get(value)
            }, 200)
        });
        $(this.selector).attr("bind", "true")
    }
    ;
    this.get = function(val) {
        var self = this;
        this.val = val;
        var data = Object.assign({}, this.queryData, this.setParams(this.val));
        $.ajax({
            url: this.url,
            data: data
        }).done(function(res) {
            if (val !== self.val)
                return;
            function compare(a, b) {
                if (a.name < b.name)
                    return -1;
                if (a.name > b.name)
                    return 1;
                return 0
            }
            var items = res.data.items.sort(compare);
            self.render(items)
        }).fail(function() {
            Buff.toast(i18n("network_request_failed"))
        })
    }
    ;
    this.render = function(items) {
        var html = '<li value="" title="' + i18n("all") + '"><span class="w-Selectsearch-img"><b class="icon icon_all"></b></span>' + i18n("all") + "</li>";
        if (items.length) {
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                html += '<li value="' + item.id + '" title="' + item.name + '"><span class="w-Selectsearch-img"><img src="' + item.goods_info.icon_url + '"></span>' + item.name + "</li>"
            }
        } else {
            html = '<li class="none">' + i18n("not_found_to_contain_the") + "“" + this.val + "”" + i18n("jewelry") + "</li>"
        }
        $(this.selector + " .w-Selectsearch-list").html(html)
    }
    ;
    var fn = function() {};
    this.val = "";
    this.selector = options.id;
    this.url = options.url;
    this.queryData = options.queryData || {};
    this.setParams = options.setParams || function(val) {
        return {
            key: val
        }
    }
    ;
    this.bind();
    this.get()
}
;
function waterFall(options) {
    this.init(options)
}
waterFall.prototype.init = function(options) {
    this.arrHeight = [];
    this.arrLeft = [];
    this.parentHeight = 0;
    this.config(options)
}
;
waterFall.prototype.config = function(options) {
    this.pageWidth = options.width;
    this.itemWidth = options.itemWidth;
    this.columns = options.colums;
    this.gap = (this.pageWidth - this.itemWidth * this.columns) / (this.columns - 1);
    this.$parent = $(options.id);
    this.parentTop = this.$parent.position().top
}
;
waterFall.prototype.isFirst = function() {
    return this.arrHeight.length < this.columns
}
;
waterFall.prototype.setPosition = function($items) {
    if (this.$parent.length < 1)
        return;
    var self = this;
    var defereds = [];
    $items.find(".pinterest-img img").each(function() {
        var defer = $.Deferred();
        if (this.complete) {
            defer.resolve()
        } else {
            $(this).load(function() {
                defer.resolve()
            })
        }
        defereds.push(defer)
    });
    $.when.apply(null, defereds).done(function() {
        self.setHeight($items)
    })
}
;
waterFall.prototype.setHeight = function($items) {
    var self = this;
    $items.each(function(index, el) {
        var $el = $(el);
        if (self.isFirst()) {
            $el.css({
                top: 0,
                left: (self.itemWidth + self.gap) * self.arrHeight.length
            });
            self.arrHeight.push(el.offsetHeight);
            self.arrLeft.push(el.offsetLeft)
        } else {
            var minHeight = Math.min.apply(self.arrHeight, self.arrHeight);
            var minIndex = $.inArray(minHeight, self.arrHeight);
            $el.css({
                top: minHeight + self.gap,
                left: self.arrLeft[minIndex]
            });
            self.arrHeight[minIndex] += $el.height() + self.gap
        }
    });
    this.setParentHeight()
}
;
waterFall.prototype.setParentHeight = function() {
    var maxHeight = Math.max.apply(this.arrHeight, this.arrHeight);
    this.parentHeight = maxHeight + this.gap;
    this.$parent.css({
        height: this.parentHeight
    })
}
;
waterFall.prototype.getClientHeight = function() {
    return this.parentHeight + this.parentTop
}
;
function TableScrollTb(options) {
    this.offset = 0;
    this.clientX = 0;
    this.width = 0;
    this.min = 0;
    this.max = 0;
    this.init(options)
}
TableScrollTb.prototype.init = function(options) {
    this.config(options);
    this.bind()
}
;
TableScrollTb.prototype.config = function(options) {
    this.$el = options.$el;
    this.$child = options.$child;
    this.width = this.$child.width();
    this.min = this.width * .5;
    this.max = this.width * 2
}
;
TableScrollTb.prototype.bind = function() {
    this.$el && this.$el.addEventListener("touchstart", this.handelDown.bind(this));
    this.bindResize()
}
;
TableScrollTb.prototype.bindResize = function() {
    var timer = null;
    var self = this;
    $(window).resize(function(event) {
        clearTimeout(timer);
        timer = setTimeout(function() {
            self.resize()
        }, 200)
    })
}
;
TableScrollTb.prototype.resize = function() {
    this.offset = 0;
    this.$child.removeAttr("style");
    this.width = this.$child.width();
    this.min = this.width * .5;
    this.max = this.width * 2
}
;
TableScrollTb.prototype.bindMove = function() {
    if (!this.$el)
        return;
    this.$el.addEventListener("touchmove", this.handelMove.bind(this));
    this.$el.addEventListener("touchend", this.handelUp.bind(this))
}
;
TableScrollTb.prototype.unbindMove = function() {
    if (!this.$el)
        return;
    this.$el.removeEventListener("touchmove", this.handelMove);
    this.$el.removeEventListener("touchend", this.handelUp)
}
;
TableScrollTb.prototype.handelDown = function(e) {
    var target = e.target;
    if (target.nodeName.toLocaleLowerCase() === "a" || target.nodeName.toLocaleLowerCase() === "img") {
        return
    }
    var touch = e.touches[0];
    this.offset = 0;
    this.clientX = touch.clientX;
    e.stopPropagation();
    e.preventDefault();
    this.bindMove()
}
;
TableScrollTb.prototype.handelMove = function(e) {
    var clientX = e.touches[0].clientX;
    var deltax = this.clientX - clientX;
    this.move(this.width - deltax);
    e.stopPropagation();
    e.preventDefault()
}
;
TableScrollTb.prototype.handelUp = function() {
    this.width = this.offset;
    this.unbindMove()
}
;
TableScrollTb.prototype.move = function(width) {
    if (width <= this.min) {
        width = this.min
    } else if (width >= this.max) {
        width = this.max
    }
    this.offset = width;
    this.$child.width(this.offset)
}
;
TableScrollTb.prototype.unbind = function() {
    this.unbindMove();
    this.$el && this.$el.removeEventListener("touchstart", this.handelDown);
    $(window).off("resize");
    this.$el = null;
    this.$child = null
}
;
jQuery.xhrPool = [];
jQuery.xhrPool.abortAll = function() {
    var requests = [];
    for (var index in this) {
        if (isFinite(index) === true) {
            requests.push(this[index])
        }
    }
    for (index in requests) {
        requests[index].abort()
    }
}
;
jQuery.xhrPool.abort = function(url) {
    for (var index in this) {
        if (typeof this[index] == "object" && this[index].url.startsWith(url)) {
            this[index].abort();
            this.remove(this[index]);
            break
        }
    }
}
;
jQuery.xhrPool.remove = function(jqXHR) {
    for (var index in this) {
        if (this[index] === jqXHR) {
            jQuery.xhrPool.splice(index, 1);
            break
        }
    }
}
;
$(document).ajaxSend(function(event, jqXHR, options) {
    jqXHR.url = options.url;
    jQuery.xhrPool.push(jqXHR)
});
$(document).ajaxComplete(function(event, jqXHR, options) {
    jQuery.xhrPool.remove(jqXHR)
});
assetTagFilter = function() {
    var container = "";
    var popup_callback = null;
    var data_observer = null;
    var show = function() {
        $(container).show();
        Buff.initSelectMulti(container + " .w-Select-Multi")
    };
    var hide = function() {
        $(container).hide()
    };
    var getHashTags = function() {
        var hashParams = {
            tag_ids: "null",
            paintseed: "null",
            tier: "null",
            paintseed_group: "null"
        };
        var tags = [];
        var tag = {};
        tag.id = $(container + " .w-Select-Multi[name=unlock_style]").attr("value");
        tag.name = $(container + " .w-Select-Multi[name=unlock_style] h3").text();
        if (tag.id) {
            tags.push(tag)
        }
        $(container + " .w-Select-Multi[name=gems] li.on h6").each(function() {
            if (!$(this).attr("value"))
                return;
            tags.push({
                id: $(this).attr("value"),
                name: $(this).text()
            })
        });
        var tag_ids = [];
        for (var i = 0; i < tags.length; i++) {
            tag_ids.push(tags[i].id)
        }
        if (tag_ids)
            hashParams["tag_ids"] = tag_ids.join(",");
        var tierValue = $(container + " .w-Select-Multi[name=tier]").attr("value");
        if (tierValue) {
            var s = tierValue.split("-");
            hashParams[s[0]] = s[1];
            var name = $(container + " .w-Select-Multi[name=tier]").find("h6[value=" + tierValue + "]").text();
            tags.push({
                id: tierValue,
                name: name || s[1]
            })
        }
        var floatRange = $(container + " .w-Select-Multi[name=float_range]").attr("value");
        if (floatRange) {
            var floats = parseFloatRange(floatRange);
            hashParams.min_paintwear = floats[0];
            hashParams.max_paintwear = floats[1]
        } else {
            hashParams.min_paintwear = hashParams.max_paintwear = ""
        }
        var fadeRange = $(container + " .w-Select-Multi[name=fade_range]").attr("value");
        if (fadeRange) {
            var fades = parseFloatRange(fadeRange);
            hashParams.min_fade = fades[0];
            hashParams.max_fade = fades[1]
        } else {
            hashParams.min_fade = hashParams.max_fade = ""
        }
        var name_tag_ele = $(container + " .w-Select-Multi[name=name_tag]");
        hashParams.name_tag = name_tag_ele.attr("value") || "";
        var extra_tag_ids = $(".w-Select-Multi[name=extra_tag_ids]");
        if (extra_tag_ids) {
            var extra_tag_ids_val = extra_tag_ids.attr("value");
            if (extra_tag_ids_val !== undefined && extra_tag_ids_val !== "custom") {
                hashParams.extra_tag_ids = extra_tag_ids_val
            }
        }
        hashParams.min_price = $.trim($(container + " .w-Counter").find(".i_Text").eq(0).val()) || "";
        hashParams.max_price = $.trim($(container + " .w-Counter").find(".i_Text").eq(1).val()) || "";
        hashParams.page_num = 1;
        return {
            tags: tags,
            hashParams: hashParams
        }
    };
    var updateHashView = function() {
        var data = getHashTags();
        updateHashData(data.hashParams)
    };
    var parseFloatRange = function(custom_paintwear_val) {
        var custom_min_val = "";
        var custom_max_val = "";
        if (custom_paintwear_val.includes("-")) {
            custom_min_val = custom_paintwear_val.split("-")[0];
            custom_max_val = custom_paintwear_val.split("-")[1]
        } else if (custom_paintwear_val.includes("≥")) {
            custom_min_val = custom_paintwear_val.split("≥")[1]
        } else if (custom_paintwear_val.includes("≤")) {
            custom_max_val = custom_paintwear_val.split("≤")[1]
        }
        return [custom_min_val, custom_max_val]
    };
    var deParseFloatRange = function(min_input_val, max_input_val) {
        var custom_painwear_val = "";
        if (max_input_val && min_input_val) {
            custom_painwear_val = min_input_val + "-" + max_input_val
        }
        if (!max_input_val && min_input_val) {
            custom_painwear_val = "≥" + min_input_val
        }
        if (max_input_val && !min_input_val) {
            custom_painwear_val = "≤" + max_input_val
        }
        return custom_painwear_val
    };
    var refreshFromHash = function() {
        $(container + " .w-Select-Multi li").removeClass("on");
        $(container + " .w-Select-Multi p").removeClass("on");
        $(container + " .w-Select-Multi").attr("value", "");
        $(container + " .w-Select-Multi").each(function() {
            $(this).find("h3").text($(this).data("title"))
        });
        var hashData = getParamsFromHash();
        var tag_ids = hashData.tag_ids;
        tag_ids = tag_ids ? tag_ids.split(",") : [];
        if (hashData.tier) {
            var value = "tier-" + hashData.tier;
            tag_ids.push(value)
        } else if (hashData.paintseed) {
            var value = "paintseed-" + hashData.paintseed;
            tag_ids.push(value)
        } else if (hashData.paintseed_group) {
            var value = "paintseed_group-" + hashData.paintseed_group;
            tag_ids.push(value)
        }
        if (tag_ids) {
            for (var i = 0; i < tag_ids.length; i++) {
                var tag_id = tag_ids[i];
                var depth1_tag = $(container + " .w-Select-Multi h6[value=" + tag_id + "]");
                var depth2_tag = $(container + " .w-Select-Multi p[value=" + tag_id + "]");
                if (depth2_tag.length > 0) {
                    depth2_tag.addClass("on");
                    depth2_tag.parents(".w-Select-Multi").attr("value", tag_id);
                    var name = depth2_tag.text();
                    depth2_tag.parents(".w-Select-Multi").find("h3").text(name)
                }
                if (depth1_tag.length > 0) {
                    depth1_tag.parents(".w-Select-Multi").attr("value", tag_id);
                    depth1_tag.parent().addClass("on");
                    var name = depth1_tag.text();
                    depth1_tag.parents(".w-Select-Multi").find("h3").text(name)
                }
                if (tag_id.indexOf("paintseed-") == 0) {
                    var input = $(container + " .w-Select-Multi[name=tier] input");
                    input.parents(".w-Select-Multi").attr("value", tag_id);
                    var paintseed = tag_id.split("-")[1];
                    input.val(paintseed);
                    input.parents(".w-Select-Multi").find("h3").text(paintseed)
                }
            }
        }
        if (!hashData.paintseed) {
            $(container + " .w-Select-Multi[name=tier] input").val("")
        }
        if (hashData.min_paintwear || hashData.max_paintwear) {
            var range = deParseFloatRange(hashData.min_paintwear, hashData.max_paintwear);
            $(container + ' .w-Select-Multi h6[value="' + range + '"]').parents("li").addClass("on");
            $(container + " .w-Select-Multi[name=float_range]").attr("value", range).find("h3").text(range)
        }
        if (hashData.min_fade || hashData.max_fade) {
            var range = deParseFloatRange(hashData.min_fade, hashData.max_fade);
            var range_text = deParseFloatRange(hashData.min_fade && hashData.min_fade + "%", hashData.max_fade && hashData.max_fade + "%");
            $(container + ' .w-Select-Multi h6[value="' + range + '"]').parents("li").addClass("on");
            $(container + " .w-Select-Multi[name=fade_range]").attr("value", range).find("h3").text(range_text)
        }
        if (hashData.name_tag) {
            var name_tag = $(container + " .w-Select-Multi[name=name_tag]").find("h6[value=" + hashData.name_tag + "]");
            name_tag.parents("li").addClass("on");
            $(container + " .w-Select-Multi[name=name_tag]").attr("value", hashData.name_tag).find("h3").text(name_tag.text())
        }
        if (hashData.extra_tag_ids) {
            var extra_tag_ids = hashData.extra_tag_ids;
            var h6_value = extra_tag_ids;
            if (["", "empty", "non_empty", "squad_combos"].indexOf(extra_tag_ids) == -1) {
                h6_value = "custom"
            }
            var h6_sel = $(container + ' .w-Select-Multi[name=extra_tag_ids] h6[value="' + h6_value + '"]').parents("li");
            h6_sel.addClass("on");
            $(container + " .w-Select-Multi[name=extra_tag_ids]").attr("value", hashData.extra_tag_ids).find("h3").text(h6_sel.text())
        }
        if (hashData.min_price) {
            $(container + " .w-Counter .i_Text").eq(0).val(hashData.min_price)
        } else {
            $(container + " .w-Counter .i_Text").eq(0).val("")
        }
        if (hashData.max_price) {
            $(container + " .w-Counter .i_Text").eq(1).val(hashData.max_price)
        } else {
            $(container + " .w-Counter .i_Text").eq(1).val("")
        }
        var sort_by = hashData.sort_by || "default";
        if (sort_by) {
            var sort_by_tag = $(container + " .w-Select-Multi[name=sort]").find('h6[value="' + sort_by + '"]');
            $(container + " .w-Select-Multi[name=sort]").attr("value", sort_by).find("h3").html(sort_by_tag.html())
        }
        $(container + " .w-Order").each(function() {
            $(this).removeClass("w-Order_asc").removeClass("w-Order_des").attr("value", "");
            var name = $(this).attr("name");
            if (sort_by.indexOf(name) > -1) {
                if (sort_by.indexOf("asc") > -1) {
                    $(this).addClass("w-Order_asc");
                    $(this).attr("value", "asc")
                } else {
                    $(this).addClass("w-Order_des");
                    $(this).attr("value", "des")
                }
            }
        })
    };
    var init = function(config) {
        container = "#" + config.container;
        popup_callback = config.popup_callback || null;
        data_observer = config.data_observer || null;
        var html = template_render("asset-tag-filter-pat", config.data);
        $(container).html(html);
        var multiEle = container + " .w-Select-Multi";
        $(document).on("click", ".tb-Order", function() {
            var element = $("div[name='sort']");
            element.children("h3:first").html(element.attr("default"))
        });
        $("body").on("change", multiEle, function() {
            var name = $(this).attr("name");
            if (name == "tier") {
                $(this).find("input").val("")
            }
            if (name == "extra_tag_ids") {
                if ($(this).attr("value") == "custom") {
                    return
                }
                if (data_observer) {
                    data_observer("last_extra_tag_ids", $(this).attr("value"))
                }
            } else if (name == "sort") {
                updateHashData({
                    page_num: 1,
                    sort_by: $(this).attr("value")
                });
                return
            }
            updateHashView()
        });
        $("body").on("change", multiEle + " input", function(event) {
            var value = $(this).val();
            if (value.length > 0) {
                var value = parseInt(value);
                if (Number.isNaN(value) || value < 0 || value > 1e3) {
                    Buff.toast(i18n("please_input_01000_between_the"), {
                        type: "error"
                    });
                    return
                }
                $(this).parents(".w-Select-Multi").attr("value", "paintseed-" + value);
                $(this).parents(".w-Select-Multi").find("li").removeClass("on")
            } else {
                $(this).parents(".w-Select-Multi").attr("value", "")
            }
            updateHashView();
            event.stopPropagation()
        });
        var popup_container = "popup-container";
        if (config.data && config.data.paintwear_choices) {
            $(container + " #custom-float-range").click(function(event) {
                event.preventDefault();
                event.stopPropagation();
                var floatRange = $(container + " .w-Select-Multi[name=float_range]").attr("value");
                var paintwear_choices = config.data.paintwear_choices;
                var custom_min_val = "";
                var custom_max_val = "";
                if (floatRange) {
                    var floats = parseFloatRange(floatRange);
                    custom_min_val = floats[0];
                    custom_max_val = floats[1]
                }
                var template_data = {
                    custom_min_placeholder: paintwear_choices[0][0],
                    custom_max_placeholder: paintwear_choices[paintwear_choices.length - 1][1],
                    custom_min_val: custom_min_val,
                    custom_max_val: custom_max_val
                };
                var html = template_render("custom-paintwear-pat", template_data);
                $("#" + popup_container).html(html);
                Popup.show("custom-paintwear-container")
            });
            var min_input_selector = "#custom-paintwear-container input[name=custom_min]";
            var max_input_selector = "#custom-paintwear-container input[name=custom_max]";
            $(document).on("focus", min_input_selector, function() {
                var min_val = $(this).attr("placeholder");
                var cur_val = $(this).val();
                if (!cur_val) {
                    $(this).val(min_val.split(".")[0] + ".")
                }
            }).on("blur", min_input_selector, function() {
                var cur_val = $(this).val();
                if (!cur_val) {
                    $(this).val("");
                    return
                }
                if (cur_val == "0.") {
                    $(this).val("");
                    return
                }
                if (cur_val < $(this).attr("placeholder")) {
                    $(this).val($(this).attr("placeholder"));
                    return
                }
                var max_val = $(max_input_selector).attr("placeholder");
                var max_input_val = $(max_input_selector).val() || max_val;
                if (cur_val > max_input_val) {
                    $(this).val(max_input_val > max_val ? max_val : max_input_val);
                    $(max_input_selector).val(cur_val > max_val ? max_val : cur_val)
                }
                if (cur_val.indexOf(".") == cur_val.length - 1) {
                    $(this).val(cur_val.replace(".", ""))
                }
            }).on("keyup", min_input_selector, function(ev) {
                var code = ev.keyCode || ev.charCode;
                $(this).val($(this).val().replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, "$1"));
                if (code == 13) {
                    if ($(this).val().length > 0) {
                        $(this).trigger("blur");
                        $("#" + popup_container + " #custom_paintwear_confirm").trigger("click")
                    }
                }
            });
            $(document).on("focus", max_input_selector, function() {
                var max_val = $(this).attr("placeholder");
                if (!max_val) {
                    return
                }
                var cur_val = $(this).val();
                if (!cur_val) {
                    $(this).val(max_val.split(".")[0] + ".")
                }
            }).on("blur", max_input_selector, function() {
                var cur_val = $(this).val();
                if (!cur_val) {
                    $(this).val("");
                    return
                }
                if (cur_val == "0.") {
                    $(this).val("");
                    return
                }
                if (cur_val > $(this).attr("placeholder")) {
                    $(this).val($(this).attr("placeholder"));
                    return
                }
                var min_val = $(min_input_selector).attr("placeholder");
                var min_input_val = $(min_input_selector).val() || min_val;
                if (cur_val < min_input_val) {
                    if (cur_val < min_input_val) {
                        $(this).val(min_input_val < min_val ? min_val : min_input_val);
                        $(min_input_selector).val(cur_val < min_val ? min_val : cur_val)
                    }
                }
                if (cur_val.indexOf(".") == cur_val.length - 1) {
                    $(this).val(cur_val.replace(".", ""))
                }
            }).on("keyup", max_input_selector, function(ev) {
                var code = ev.keyCode || ev.charCode;
                $(this).val($(this).val().replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, "$1"));
                if (code == 13) {
                    if ($(this).val().length > 0) {
                        $(this).trigger("blur");
                        $("#" + popup_container + " #custom_paintwear_confirm").trigger("click")
                    }
                }
            });
            $(document).on("click", "#" + popup_container + " #custom_paintwear_reset", function() {
                $(min_input_selector).val("");
                $(max_input_selector).val("");
                Popup.hide(popup_container);
                if (popup_callback) {
                    popup_callback({
                        event: "custom_paintwear_reset",
                        data: {}
                    })
                }
            });
            $(document).on("click", "#" + popup_container + " #custom_paintwear_confirm", function() {
                Popup.hide();
                var custom_painwear_val = deParseFloatRange($(min_input_selector).val().toString(), $(max_input_selector).val().toString());
                if (popup_callback) {
                    popup_callback({
                        event: "custom_paintwear_confirm",
                        data: {
                            custom_painwear_val: custom_painwear_val
                        }
                    })
                }
            })
        }
        var popup_container = "popup-container";
        if (config.data && config.data.has_fade_name) {
            $(container + " #custom-fade-range").click(function(event) {
                event.preventDefault();
                event.stopPropagation();
                var floatRange = $(container + " .w-Select-Multi[name=fade_range]").attr("value");
                var custom_min_val = "";
                var custom_max_val = "";
                if (floatRange) {
                    var floats = parseFloatRange(floatRange);
                    custom_min_val = floats[0];
                    custom_max_val = floats[1]
                }
                var template_data = {
                    custom_min_placeholder: "79.0",
                    custom_max_placeholder: "100.0",
                    custom_min_val: custom_min_val,
                    custom_max_val: custom_max_val
                };
                var html = template_render("custom-fade-pat", template_data);
                $("#" + popup_container).html(html);
                Popup.show("custom-fade-container")
            });
            var min_fade_input_selector = "#custom-fade-container input[name=custom_min]";
            var max_fade_input_selector = "#custom-fade-container input[name=custom_max]";
            $(document).on("focus", min_fade_input_selector, function() {
                var min_val = $(this).attr("placeholder");
                var cur_val = $(this).val();
                if (!cur_val) {
                    $(this).val(min_val)
                }
            }).on("blur", min_fade_input_selector, function() {
                var cur_val = $(this).val();
                if (!cur_val) {
                    $(this).val("");
                    return
                }
                var cur_val_num = parseFloat(cur_val);
                if (cur_val_num < $(this).attr("placeholder")) {
                    $(this).val($(this).attr("placeholder"));
                    return
                }
                var max_val = parseFloat($(max_fade_input_selector).attr("placeholder"));
                var max_input_val = $(max_fade_input_selector).val() || max_val;
                if (cur_val_num > max_input_val) {
                    $(this).val(max_input_val > max_val ? max_val : max_input_val);
                    $(max_fade_input_selector).val(cur_val_num > max_val ? max_val : cur_val_num)
                }
                if (cur_val.indexOf(".") == cur_val.length - 1) {
                    $(this).val(cur_val.replace(".", ""))
                }
            }).on("keyup", min_fade_input_selector, function(ev) {
                var code = ev.keyCode || ev.charCode;
                $(this).val($(this).val().replace(/^\D*(\d*(?:\.\d{0,1})?).*$/g, "$1"));
                if (code == 13) {
                    if ($(this).val().length > 0) {
                        $(this).trigger("blur");
                        $("#" + popup_container + " #custom_fade_confirm").trigger("click")
                    }
                }
            });
            $(document).on("focus", max_fade_input_selector, function() {
                var max_val = $(this).attr("placeholder");
                if (!max_val) {
                    return
                }
                var cur_val = $(this).val();
                if (!cur_val) {
                    $(this).val(max_val)
                }
            }).on("blur", max_fade_input_selector, function() {
                var cur_val = $(this).val();
                if (!cur_val) {
                    $(this).val("");
                    return
                }
                var cur_val_num = parseFloat(cur_val);
                if (cur_val_num > $(this).attr("placeholder")) {
                    $(this).val($(this).attr("placeholder"));
                    return
                }
                var min_val = parseFloat($(min_fade_input_selector).attr("placeholder"));
                var min_input_val = $(min_fade_input_selector).val() || min_val;
                if (cur_val_num < min_input_val) {
                    if (cur_val < min_input_val) {
                        $(this).val(min_input_val < min_val ? min_val : min_input_val);
                        $(min_fade_input_selector).val(cur_val < min_val ? min_val : cur_val)
                    }
                }
                if (cur_val.indexOf(".") == cur_val.length - 1) {
                    $(this).val(cur_val.replace(".", ""))
                }
            }).on("keyup", max_fade_input_selector, function(ev) {
                var code = ev.keyCode || ev.charCode;
                $(this).val($(this).val().replace(/^\D*(\d*(?:\.\d{0,1})?).*$/g, "$1"));
                if (code == 13) {
                    if ($(this).val().length > 0) {
                        $(this).trigger("blur");
                        $("#" + popup_container + " #custom_fade_confirm").trigger("click")
                    }
                }
            });
            $(document).on("click", "#" + popup_container + " #custom_fade_reset", function() {
                $(min_fade_input_selector).val("");
                $(max_fade_input_selector).val("");
                Popup.hide(popup_container);
                if (popup_callback) {
                    popup_callback({
                        event: "custom_fade_reset",
                        data: {}
                    })
                }
            });
            $(document).on("click", "#" + popup_container + " #custom_fade_confirm", function() {
                Popup.hide();
                var min_input_text = $(min_fade_input_selector).val().toString();
                var max_input_text = $(max_fade_input_selector).val().toString();
                var custom_fade_val = deParseFloatRange(min_input_text, max_input_text);
                var custom_fade_text = deParseFloatRange(min_input_text && min_input_text + "%", max_input_text && max_input_text + "%");
                if (popup_callback) {
                    popup_callback({
                        event: "custom_fade_confirm",
                        data: {
                            custom_fade_val: custom_fade_val,
                            custom_fade_text: custom_fade_text
                        }
                    })
                }
            })
        }
        $(container + " .w-Counter").hover(function() {
            $(this).find(".w-Counter-pannel").show()
        }, function() {
            $(this).find(".w-Counter-pannel").hide()
        }).on("click", ".i_Btn_sub", function() {
            var $counter = $(this).parent().parent();
            $counter.find(".i_Text").val("");
            updateHashView()
        }).on("click", ".i_Btn_main", function() {
            updateHashView()
        });
        Buff.pricePatten("input[name=min_price]");
        Buff.pricePatten("input[name=max_price]");
        $(window).on("hashchange", refreshFromHash);
        refreshFromHash();
        return this
    };
    return {
        init: init,
        show: show,
        hide: hide
    }
}
;
var getParams = function(query) {
    var query = query || window.location.search.substring(1);
    var params = {};
    var sPageURL = decodeURIComponent(query);
    if (sPageURL == "") {
        return {}
    }
    var sURLVariables = sPageURL.split("&");
    for (var i = 0; i < sURLVariables.length; i++) {
        var param = sURLVariables[i].split("=");
        params[param[0]] = param[1]
    }
    return params
};
var getParamsFromHash = function() {
    if (!window.location.hash) {
        return {}
    }
    return getParams(window.location.hash.substring(1))
};
var updateHash = function(key, value) {
    var params = getParamsFromHash();
    if (value === undefined || value === "") {
        delete params[key]
    } else {
        params[key] = value
    }
    window.location.hash = "#" + $.param(params).replace(/\+/g, "%20")
};
var updateHash2 = function(key, value) {
    var params = getParamsFromHash();
    if (value === undefined || value === "") {
        delete params[key]
    } else {
        params[key] = value
    }
    var baseUrl = window.location.href.split("#")[0];
    window.location.replace(baseUrl + "#" + $.param(params).replace(/\+/g, "%20"))
};
var updateHashData = function(data) {
    var params = getParamsFromHash();
    for (var key in data) {
        var value = data[key];
        if (value.length < 1 || value === "null") {
            delete params[key]
        } else {
            params[key] = value
        }
    }
    window.location.hash = "#" + $.param(params).replace(/\+/g, "%20")
};
var goBack = function(back_url) {
    if (document.referrer) {
        window.history.back()
    } else {
        window.location.href = back_url
    }
};
var formatPriceBigYuan = function(price, no_symbol) {
    return (no_symbol === undefined ? "¥ " : "") + formatPrice(price, "big")
};
var formatPriceNormalYuan = function(price, no_symbol) {
    return (no_symbol === undefined ? "¥ " : "") + formatPrice(price, "normal")
};
var formatPriceYuan = function(price, no_symbol) {
    return (no_symbol === undefined ? "¥ " : "") + formatPrice(price)
};
var formatPriceDollar = function(price, no_symbol) {
    return (no_symbol === undefined ? "$ " : "") + formatPrice(price)
};
var formatPriceBigCustom = function(price, no_symbol, original_currency) {
    return formatPriceCustom(price, no_symbol, "big", original_currency)
};
var formatPriceNormalCustom = function(price, no_symbol, original_currency) {
    return formatPriceCustom(price, no_symbol, "normal", original_currency)
};
var formatPriceCustom = function(price, no_symbol, type, original_currency) {
    var rate = g.currency.rate_base_cny;
    if (original_currency == "USD") {
        rate = g.currency.rate_base_usd
    }
    var new_price = price * rate;
    new_price = new_price.toFixed(2);
    if (price > 0 && new_price == "0.00") {
        new_price = "0.01"
    }
    return (no_symbol === undefined ? g.currency.symbol + " " : "") + formatPrice(new_price, type)
};
var formatPrice = function(price, type) {
    var _p = parseFloat(price).toFixed(2).replace(/0+$/, "").replace(/\.+$/, "");
    var _s = _p.split(".");
    if (_s.length > 1) {
        if (type == "big") {
            return "<big>" + _s[0] + "</big>." + _s[1]
        } else if (type == "normal") {
            return "" + _p
        } else {
            return "" + _s[0] + "<small>." + _s[1] + "</small>"
        }
    } else {
        if (type == "big") {
            return "<big>" + _s[0] + "</big>"
        }
        return "" + _p
    }
};
var isClientVersionGreater = function(ios_version, android_version) {
    if (typeof WebViewInfo == "undefined" || !WebViewInfo.webview_from) {
        return false
    }
    var os = getDeviceOS();
    if (os == "ios") {
        var version = WebViewInfo.webview_app_version;
        return version.split(".") >= ios_version.split(".")
    } else if (os == "android") {
        var version_code = WebViewInfo.webview_app_version_code;
        return parseInt(version_code) >= parseInt(android_version)
    }
    return false
};
var renderPagination = function(config) {
    var pager_name = config.pager_name || ".pager";
    if (config.total_count < 1 || config.page_size >= config.total_count) {
        $(pager_name).html("").hide();
        return
    }
    $(pager_name).show();
    $(pager_name).pagination({
        items: config.total_count,
        itemsOnPage: config.page_size,
        displayedPages: config.displayed_pages || 9,
        cssStyle: "light-theme",
        currentPage: config.page_num,
        hrefTextPrefix: "#page_num=",
        prevText: i18n("prev_page"),
        nextText: i18n("next_page"),
        onPageClick: config.onPageClick
    });
    if (config.show_size_select == true) {
        var size_selects = config.size_selects || [30, 50, 100, 200];
        page_size_html = '<div id="search-page_size" class="w-Select" name="page_size" value="' + config.page_size + '">            <h3>' + i18n("page_size") + config.page_size + '</h3>            <i class="icon icon_drop"></i>            <ul>';
        for (var i = 0; i < size_selects.length; i++) {
            var page_size = size_selects[i];
            page_size_html += '<li value="' + page_size + '">' + i18n("page_size") + page_size + "</li>"
        }
        page_size_html += "</ul></div>";
        $(pager_name).append(page_size_html);
        Buff.initSelect("#search-page_size")
    }
};
var updateSearch = function(key, value) {
    var params = getParams();
    if (value.length < 1 || value === "null") {
        delete params[key]
    } else {
        params[key] = value
    }
    if ("page_num"in params) {
        delete params["page_num"]
    }
    updateHash("page_num", undefined);
    window.location.search = $.param(params).replace(/\+/g, "%20")
};
var updateSearchData = function(data) {
    var params = getParams();
    for (var key in data) {
        var value = data[key];
        if (value.length < 1 || value === "null") {
            delete params[key]
        } else {
            params[key] = value
        }
        if ("page_num"in params) {
            delete params["page_num"]
        }
        updateHash("page_num", undefined)
    }
    window.location.search = $.param(params).replace(/\+/g, "%20")
};
var updateSearchPage = function(key, value) {
    var params = getParams() || {};
    if (value > 0) {
        params[key] = value
    } else {
        delete params[key]
    }
    window.location.search = $.param(params).replace(/\+/g, "%20")
};
function randomstring(L) {
    var s = "";
    var randomchar = function() {
        var n = Math.floor(Math.random() * 62);
        if (n < 10)
            return n;
        if (n < 36)
            return String.fromCharCode(n + 55);
        return String.fromCharCode(n + 61)
    };
    while (s.length < L)
        s += randomchar();
    return s
}
function formatRelativeTime(timestamp) {
    var now = new Date / 1e3;
    var seconds = Math.abs(now - timestamp);
    if (seconds <= 1) {
        return "刚刚"
    }
    var bases = [60, 60, 24, 365, 100];
    var units = ["秒", "分钟", "小时", "天", "年", "世纪"];
    var value = parseInt(seconds);
    for (var idx = 0; idx < bases.length; idx++) {
        if (value < bases[idx]) {
            return "" + value + units[idx] + (now > timestamp ? "前" : "后")
        }
        value = Math.floor(value / bases[idx])
    }
    return "" + values + "秒"
}
function formatTimestamp(ts, format) {
    return moment(ts, "X").format(format || "YYYY-MM-DD HH:mm")
}
if (typeof template != "undefined") {
    template.defaults.imports.formatTimestamp = formatTimestamp;
    template.defaults.imports.formatRelativeTime = formatRelativeTime;
    template.defaults.imports.formatPriceYuan = formatPriceYuan;
    template.defaults.imports.formatPriceDollar = formatPriceDollar;
    template.defaults.imports.formatPriceBigYuan = formatPriceBigYuan;
    template.defaults.imports.formatPriceNormalYuan = formatPriceNormalYuan;
    template.defaults.imports.formatPriceCustom = formatPriceCustom;
    template.defaults.imports.formatPriceBigCustom = formatPriceBigCustom;
    template.defaults.imports.formatPriceNormalCustom = formatPriceNormalCustom;
    template.defaults.imports.formatPrice = formatPrice;
    template.defaults.imports.parseFloat = parseFloat;
    template.defaults.imports.JSON = JSON;
    template.defaults.imports.i18n = i18n;
    template.defaults.imports.ceil = Math.ceil;
    template.defaults.imports.moment = moment;
    template.defaults.imports.abs = Math.abs;
    template.defaults.imports.g = g
}
var _template_cache = {};
var template_render = function(pat_id, data) {
    var cache = _template_cache[pat_id];
    if (cache === undefined) {
        var elem = document.getElementById(pat_id);
        if (elem) {
            var source = elem.value || elem.innerHTML;
            cache = template.compile(source);
            _template_cache[pat_id] = cache
        }
    }
    if (cache !== undefined) {
        return cache(data)
    }
};
var sendRequest = function(url, config) {
    config.error = config.error || function(resp) {
        if (config.showLoading !== false) {
            $("#loading-cover").hide()
        }
        if (resp.statusText != "abort") {
            if (config.showError != false) {
                if (["timeout", "error"].indexOf(resp.statusText) > -1) {
                    this.tryCount++;
                    if (this.tryCount <= this.retryLimit) {
                        $.ajax(this);
                        return
                    }
                    Buff.toast(i18n("network_error"))
                } else if (resp.status == 500) {
                    Buff.toast(i18n("system_busy_error"))
                }
            }
        }
    }
    ;
    config.cache = config.cache || false;
    config.timeout = config.timeout || 5e3;
    config.ignoreCode = config.ignoreCode || [];
    config.tryCount = 0;
    config.retryLimit = config.method.toUpperCase() == "POST" ? 0 : 2;
    if (config.showLoading !== false) {
        $("#loading-cover").show()
    }
    var success = config.success;
    config.success = function(data) {
        if (config.showLoading !== false) {
            $("#loading-cover").hide()
        }
        if (config.ignoreCode.indexOf(data.code) > -1) {
            if (data.code == "OK" && data.msg != null) {
                Buff.toast(data.msg)
            }
            success(data);
            return
        }
        if (data.code === "Login Required") {
            loginModule.showLogin()
        } else if (data.code == "Internal Server Error") {
            if (config.showError != false) {
                Buff.toast(i18n("system_busy_error"))
            }
        } else if (data.code == "Action Forbidden") {
            Buff.toast(data.error, {
                type: "error"
            })
        } else if (data.code == "User Frozen") {
            Buff.toast(data.error, {
                type: "error"
            })
        } else if (data.code == "Steam Binding Required") {
            Buff.alert({
                title: i18n("unbound_steam"),
                hideCancel: true,
                message: i18n("unbound_steam_notice"),
                confirmText: i18n("go_to_bind"),
                success: function() {
                    window.open("/user-center/profile", "_blank")
                }
            })
        } else if (data.code == "Steam Trade URL Binding Required") {
            Buff.alert({
                title: i18n("set_up_steam_trade_url"),
                message: data.error + '<a href="/help#N_steam_setting" target="_blank">如何绑定</a>',
                success: function() {
                    window.open("/user-center/profile")
                },
                confirmText: i18n("go_to_bind")
            })
        } else if (data.code == "Steam Trade Hold Duration Invalid") {
            Buff.alert({
                title: i18n("prompt"),
                message: data.error,
                confirmText: i18n("go_to_view"),
                success: function() {
                    window.open("/help#why_cant_i_trade", "_blank")
                }
            })
        } else if (data.code == "Steam Trade Limit") {
            Buff.alert({
                title: i18n("prompt"),
                message: i18n("steam_trade_limit"),
                confirmText: i18n("go_to_view"),
                success: function() {
                    window.open("/help#before_trade", "_blank")
                }
            })
        } else if (data.code == "Realname Required") {
            Buff.alert({
                title: i18n("prompt"),
                message: data.error,
                confirmText: i18n("go_to_verify"),
                success: function() {
                    bindCard.show_cert_popup(null, function() {
                        document.location.reload()
                    })
                }
            })
        } else if (data.code == "Epay Account Required") {
            Buff.alert({
                title: i18n("prompt"),
                message: data.error,
                confirmText: i18n("go_to_bind_card"),
                success: function() {
                    var realname = null;
                    if (data.extra.name) {
                        realname = data.extra
                    }
                    bindCard.show_bind_card_popup(realname, function() {
                        document.location.reload()
                    })
                }
            })
        } else if (data.code == "Epay Account Grade Failure") {
            Buff.alert({
                title: i18n("prompt"),
                message: data.error,
                hideCancel: true,
                confirmText: i18n("ok"),
                success: function() {}
            })
        } else if (data.code == "Steam API Key Not Set" || data.code == "Steam API Key Invalid") {
            Buff.alert({
                title: i18n("prompt"),
                message: data.error,
                success: function() {
                    window.open("/user-center/profile")
                },
                confirmText: i18n("go_to_set")
            })
        } else if (data.code == "Backpack Is Private") {
            Buff.alert({
                title: i18n("prompt"),
                message: data.error,
                confirmText: i18n("go_to_set"),
                success: function() {
                    window.open("https://steamcommunity.com/my/edit/settings")
                }
            })
        } else if (data.code == "Steam Logged In Needs Verification") {
            loggedInFromSteamVerifyManager(data.extra.mobile).init()
        } else {
            if (data.code == "OK" && data.msg != null) {
                Buff.toast(data.msg)
            } else if (data.code != "OK") {
                if (data.confirm_entry) {
                    var ce = data.confirm_entry;
                    Buff.alert({
                        title: ce.title,
                        message: ce.message,
                        hideCancel: ce.button_cancel == "",
                        cancelText: ce.button_cancel,
                        hideConfirm: ce.button_noted == "" && ce.button_open_url == "",
                        confirmText: ce.button_noted || ce.button_open_url,
                        success: function() {
                            if (ce.entry) {
                                window.open(ce.entry.url)
                            }
                            Popup.hide()
                        }
                    });
                    return
                }
            }
            success(data)
        }
    }
    ;
    var method = config.method.toUpperCase();
    if (["POST", "PUT", "DELETE", "PATCH"].indexOf(method) > -1) {
        config.contentType = config.contentType || "application/json";
        config.headers = config.headers || {};
        var _csrf_token = getCookie("csrf_token");
        config.headers["X-CSRFToken"] = _csrf_token;
        if (config.contentType === "application/json") {
            config.data = JSON.stringify(config.data)
        }
    }
    return $.ajax(url, config)
};
function isTextSelected(input) {
    if (typeof input.selectionStart == "number") {
        return input.selectionStart != input.value.length
    } else if (typeof document.selection != "undefined") {
        input.focus();
        return document.selection.createRange().text == input.value
    }
}
function getUrlRelativePath() {
    var url = document.location.toString();
    var arrUrl = url.split("//");
    var start = arrUrl[1].indexOf("/");
    var relUrl = arrUrl[1].substring(start);
    if (relUrl.indexOf("?") != -1) {
        relUrl = relUrl.split("?")[0]
    }
    if (relUrl.indexOf("#") != -1) {
        relUrl = relUrl.split("#")[0]
    }
    return relUrl
}
function openPageOnNewTab(url) {
    var a = $("<a href='" + url + "' target='_blank' style='display:none'>buff</a>").get(0);
    var e = document.createEvent("MouseEvents");
    e.initEvent("click", true, true);
    a.dispatchEvent(e)
}
function getCookie(name) {
    var match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
    if (match) {
        var result = "";
        try {
            result = decodeURIComponent(match[2])
        } catch (error) {}
        return result
    }
    return ""
}
function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date;
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3);
        expires = "; expires=" + date.toUTCString()
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/"
}
function removeCookie(cn, path) {
    document.cookie = cn + "=;Path=" + (path || "/") + ";"
}
function isUserLogined() {
    if (g.user)
        return true;
    return false
}
var gameNavigator = function() {
    var _params_to_keep = [];
    var switchGame = function(game, navpre) {
        document.cookie = "game=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
        document.cookie = "game=" + game + "; path=/";
        var get_keep_params = function() {
            var ext_params = [];
            var data = getParams();
            for (var i = 0; i < _params_to_keep.length; i++) {
                var param = _params_to_keep[i];
                if (data[param]) {
                    ext_params.push(param + "=" + data[param])
                }
            }
            return ext_params.join("&")
        };
        if (g.game == game)
            return;
        if (navpre) {
            if (navpre == "/market/" + g.game) {
                window.location.href = navpre.replace(g.game, game)
            } else {
                if (navpre == "/market/sell_order/on_sale" && _params_to_keep.length) {
                    window.location.href = navpre + "?game=" + game + "&" + get_keep_params()
                } else {
                    window.location.href = navpre + "?game=" + game
                }
            }
        } else {
            var ext_params = _params_to_keep.length > 0 ? get_keep_params() : "";
            var url = window.location.pathname + "?game=" + game + "&" + ext_params;
            window.location.href = url
        }
    };
    var setKeepParams = function(params) {
        _params_to_keep = params
    };
    return {
        switchGame: switchGame,
        setKeepParams: setKeepParams
    }
}();
var updateNavbarCashAmount = function() {
    sendRequest("/api/asset/get_brief_asset/", {
        method: "GET",
        dataType: "json",
        showLoading: false,
        success: function(data) {
            $("#navbar-cash-amount").html(formatPriceYuan(data.data.cash_amount))
        }
    })
};
function sleep(delay) {
    var start = (new Date).getTime();
    while ((new Date).getTime() < start + delay)
        ;
}
function sendNotification(config) {
    if (localStorage.getItem("_notification_" + config.tag)) {
        return
    } else {
        localStorage.setItem("_notification_" + config.tag, true)
    }
    if (Notification && Notification.permission === "granted") {
        var n = new Notification(config.title,{
            body: config.body,
            tag: config.tag,
            icon: "/static/images/favicon.ico"
        });
        n.onclick = config.onclick
    } else if (Notification && ["default", "denied"].indexOf(Notification.permission) > -1) {
        Notification.requestPermission(function(status) {
            if (Notification.permission !== status) {
                Notification.permission = status
            }
            if (status == "granted") {
                var n = new Notification(config.title,{
                    body: config.body,
                    tag: config.tag,
                    icon: "/static/images/favicon.ico"
                });
                n.onclick = config.onclick
            }
        })
    }
}
var uploadFile = function(options) {
    if (options.file == undefined)
        return;
    if (options.file.size > options.max_file_size) {
        alert("允许上传的最大图片为： " + humanFileSize(options.max_file_size, true));
        return
    }
    var error = options.error || Buff.toast;
    var xhr = new XMLHttpRequest;
    xhr.open("POST", options.upload_url);
    xhr.upload.onprogress = options.onprogress;
    xhr.onload = function() {
        switch (xhr.status) {
        case 200:
            var data = JSON.parse(xhr.responseText);
            options.callback(data);
            break;
        case 400:
            if (xhr.responseText == "File Size Invalid") {
                error("悲剧，您上传的文件超过5M了！！")
            } else if (xhr.responseText == "File Type Invalid") {
                error("矮油，只能上传图片哦！！")
            } else if (xhr.responseText == "Require Upload File") {
                error("没有选中图片呀！")
            } else {
                error("这不科学，上传出现了意想不到的错误，赶紧联系管理员！！")
            }
            break;
        default:
            error("这不科学，上传出现了意想不到的错误，赶紧联系管理员！！")
        }
    }
    ;
    xhr.onerror = function() {
        error("网络异常，请稍后重试！")
    }
    ;
    xhr.setRequestHeader("Authorization", options.token);
    xhr.send(options.file)
};
function getDeviceOS() {
    var userAgent = navigator.userAgent || navigator.vendor || window.opera;
    if (/android/i.test(userAgent)) {
        return "android"
    }
    if (/iPad|iPhone|iPod/i.test(userAgent) && !window.MSStream) {
        return "ios"
    }
    return "web"
}
var callNative = function(api, params) {
    if (typeof WebViewInfo == "undefined" || !WebViewInfo.webview_from) {
        return
    }
    var params = params || {};
    if (getDeviceOS() === "android") {
        var data = JSON.stringify({
            api: api,
            params: JSON.stringify(params)
        });
        try {
            var androidApiObject = buffAndroidApi;
            var token = "";
            while (token.length < 40) {
                token += ("" + Math.random()).substr(2)
            }
            if (prompt(JSON.stringify({
                api: api,
                token: token
            })) === "OK") {
                return androidApiObject.call(token, data)
            }
        } catch (e) {
            if (e instanceof ReferenceError) {
                try {
                    return prompt(data)
                } catch (e) {
                    console.log(e)
                }
            }
        }
        return null
    } else if (getDeviceOS() === "ios") {
        try {
            window.webkit.messageHandlers[api].postMessage(JSON.stringify(params))
        } catch (e) {
            return null
        }
    } else {
        return
    }
};
function setClipboard(value) {
    var tempInput = document.createElement("input");
    tempInput.style = "position: absolute; left: -1000px; top: -1000px";
    tempInput.value = value;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput)
}
function escapeHtml(unsafe) {
    return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;")
}
var htmlDecode = function(input) {
    var e = document.createElement("textarea");
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue
};
var initCustomCurrency = function(ele) {
    if (ele == undefined) {
        var currency = g.currency.code.toLowerCase();
        var sheet = document.createElement("style");
        sheet.innerHTML = ".hide-" + currency + " {display:none;}";
        document.body.appendChild(sheet);
        ele = document
    }
    $(ele).find(".custom-currency").each(function() {
        var price = parseFloat($(this).data("price"));
        var no_symbol = $(this).data("no-symbol");
        var type = $(this).data("type");
        var original_currency = $(this).data("original-currency");
        $(this).replaceWith(formatPriceCustom(price, no_symbol, type, original_currency))
    })
};
var initLocalTimeDisplay = function(ele) {
    if (ele == undefined) {
        ele = document
    }
    $(ele).find(".moment-ts").each(function() {
        $(this).text(moment($(this).data("ts") * 1e3).format($(this).data("fmt")))
    })
};
if (typeof Object.assign != "function") {
    Object.assign = function(target, varArgs) {
        "use strict";
        if (target == null) {
            throw new TypeError("Cannot convert undefined or null to object")
        }
        var to = Object(target);
        for (var index = 1; index < arguments.length; index++) {
            var nextSource = arguments[index];
            if (nextSource != null) {
                for (var nextKey in nextSource) {
                    if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                        to[nextKey] = nextSource[nextKey]
                    }
                }
            }
        }
        return to
    }
}
String.prototype.gblen = function() {
    var len = 0;
    for (var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) {
            len += 2
        } else {
            len++
        }
    }
    return len
}
;
String.prototype.getGblenPosition = function(dstLength) {
    var len = 0;
    for (var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) {
            len += 2
        } else {
            len++
        }
        if (len > dstLength) {
            return i
        }
    }
    return this.length - 1
}
;
function wxPayUpdateRemainTime(timeout) {
    var minutes = 0
      , seconds = 0;
    if (timeout > 0) {
        minutes = Math.floor(timeout / 60);
        seconds = timeout % 60
    }
    var text = minutes + i18n("minutes") + seconds + i18n("seconds");
    $("#pay-remain-time").text(text)
}
function wxPayShowQrcode(price, url, pay_expire_timeout, close_callback) {
    $("#j_popup_wx").remove();
    var html = template_render("wx_pay_pat", {
        price: price
    });
    $("body").append(html);
    $("#wx-pay-qrcode").html("");
    new QRCode(document.getElementById("wx-pay-qrcode"),{
        text: url,
        width: 140,
        height: 140
    });
    $("#wx-pay-qrcode").attr("title", "");
    wxPayUpdateRemainTime(pay_expire_timeout);
    $("#j_popup_wx .popup-close").click(function() {
        Popup.hide();
        if ($("#j_popup_wx").hasClass("expired")) {
            return
        }
        if (close_callback)
            close_callback()
    });
    Popup.hide();
    Popup.show("j_popup_wx")
}
function payWaitResult(order_id, pay_method, wait_second, check_func) {
    var WAIT_SECOND = wait_second;
    var check_result_return = false;
    var wait_handler = undefined;
    var dtd = $.Deferred();
    dtd.done(function() {
        check_result_return = true;
        clearInterval(wait_handler);
        wait_handler = undefined;
        Popup.hide();
        $("#loading-cover").hide()
    });
    dtd.fail(function() {
        check_result_return = true;
        clearInterval(wait_handler);
        wait_handler = undefined;
        Popup.hide();
        $("#loading-cover").hide();
        Buff.alert({
            title: i18n("prompt"),
            message: i18n("pay_failed"),
            hideCancel: true,
            success: function() {
                window.location.reload()
            }
        })
    });
    dtd.progress(function() {
        check_result_return = true
    });
    var wait = 0;
    wait_handler = setInterval(function() {
        wait += 1;
        if (wait == 1 || wait <= WAIT_SECOND && check_result_return) {
            check_result_return = false;
            check_func(order_id, dtd)
        } else if (wait > WAIT_SECOND) {
            clearInterval(wait_handler);
            wait_handler = undefined;
            if (pay_method == BuffConfig.PayMethod.WX_PAGE) {
                $("#j_popup_wx").addClass("expired");
                $("#j_popup_wx .popup-cont.paying").hide();
                $("#j_popup_wx .popup-cont.expired").show()
            } else {
                Popup.hide();
                $("#loading-cover").hide();
                Buff.alert({
                    title: i18n("payment"),
                    message: i18n("payment_system_is_busy_please"),
                    hideCancel: true,
                    success: function() {
                        window.location.reload()
                    }
                })
            }
        }
        if (pay_method == BuffConfig.PayMethod.WX_PAGE) {
            wxPayUpdateRemainTime(Math.max(WAIT_SECOND - wait, 0))
        }
    }, 1e3)
}
i18nData.updateData("en", {
    "1_seconds": "1 second",
    _piece_of_goods_has: "items fail because it has already been purchased</p>",
    _piece_of_goods_off: "items succeed</p>",
    a_period_of_time_: "a period of time: ",
    a_picture_is_not_uploaded: "Some images have not been uploaded successfully",
    a_successful_purchase: "Success",
    access_to_the_steam_encounters: "Got a problem with Steam?",
    account_can_be_withdraw_the: "Unable to withdraw, insufficient balance in the BUFF Balance-Other",
    acknowledgment_is_bound_to_the: "Are you sure to bind to this Steam account?<br>Steam nickname：",
    acquisition_fee_failed_please_try: "Failed to get the fee, please try again later",
    add_a_description: "Add a description",
    add_description: "Add a description",
    add_in_5_minutes_to: "Please send offer in BUFF APP within 5 minutes.",
    add_in_the_buyers_payment: " Please deliver within 12 hours after the buyer pays, otherwise the item will be removed from sale and your selling function will be banned.",
    add_the_other_card: "Add another bank card",
    all: "All",
    already_have_an_account_click: "Click here to login",
    analysis: "Inspecting",
    analysis_figure: "Screenshot",
    api_key_format_error: "API key format error",
    api_key_successfully_set: "Success",
    application_authentication_failure_please_contact: "Verification failed, please contact support",
    artificial_assist: "Contact Support",
    authentication: "Verification",
    back_for_refresh: "Back for refresh",
    backpack_capacity_is_insufficient_can: "The backpack has insufficient capacity to continue buying",
    bargain_price_must_be_lower: "The bargain price must be lower than the sale price",
    being_prepaid_in: "Topping up",
    beware_of_phishing_scams_please: "Beware of scams, please check if the API key was created? If it was maliciously created, please delete it and change Steam password immediately.",
    binding_acknowledgment: "Confirm",
    binding_steam: "Bind Steam",
    binding_steam_before_you_can: "Connect your steam account to enjoy buff.",
    binding_transaction_link_the_immediate: "Set your steam trade url to begin trading on BUFF",
    bound_to_fail: "Failure",
    buff_backpack_capacity_is_insufficient: "BUFF backpack has insufficient capacity and has been adjusted to buy the maximum quantity",
    buy_price_cannot_be_less: "The purchase price cannot be less than ￥0.01",
    buy_pubgrecycled_transactionitems_not_get: "PUBG items are not withdrawable",
    buy_success: "Success",
    buying_in_bulk_quantity_can: "The number of bulk buy cannot exceed",
    buying_in_bulk_results: "Result",
    can_not_supply_your_own: "Can't supply the items you purchase",
    cancel: "Cancel",
    cancel_buying_success: "Success",
    cancel_delivery_success: "Success",
    cancel_recommend: "Cancel recommend",
    cancel_the_shipment: "Cancel deliver",
    cannot_be_resolved_the_goods: "Unable to inspect, the item has been sold or the network is bad",
    cannot_purchase_your_own_items: "Can't buy your own items",
    card_limit_is_reached: "Bank card reaches the upper limit",
    cardsp: "bank cards</p>",
    century: "Century",
    change_price_of_failure: "Failure",
    clear_the_api_key_after: "After clearing the API key, your store will be offline and items will not be bought. Are you sure you want to clear?",
    click_on_upload_picture: "Click to upload image",
    click_to_collapse: "Collapse",
    click_to_expand: "Expand",
    close_failed_please_try_again: "Fail to close, try again",
    complete: "Complete",
    confirm: "Confirm",
    confirm_and_opened: "Open",
    confirm_clear: "Clear",
    confirm_leave: "Leave",
    confirm_to_cancel_the_transaction: "Confirm",
    confirmation_of_payment: "Confirm",
    "congratulations_to_you!_welcome_to": "Welcome to BUFF, you can start trading now!",
    consignment_goods_shelf_will_be: "The consignment items will be returned to your BUFF backpack after they are removed.",
    content_length_can_not_be: "Content length cannot be greater than 1024 characters",
    continue_to_pay: "Continue to pay",
    counteroffer_price_cannot_be_lower: "The bargain price must be higher than the minimum bid price",
    counteroffer_request_has_been_sent: "Bargain request has been sent",
    create_a_package_of_trading: "Success",
    create_buying_success: "Success",
    csgo_deposit_notice: 'Due to changes in the trade rules of CS:GO/DOTA2, the items wiil be available for trade again after 7 days.<a href="/help#csgo_trade_cooldown" target="_blank">CS:GO/DOTA2交易机制改动</a>',
    currently_does_not_support_the: "The card number is not supported currently. Please change the card.",
    currently_have_to_wait_for: "There is still a feedback waiting for replying. If you still need feedback, please go to supplementary.",
    day: "day",
    days: "days",
    delete_confirmation: "Confirmation",
    delete_failed: "Failure",
    delivery_prompt: "Notification",
    delivery_timeout: "Delivery timeout",
    deposit_backpack: "Deposit",
    deposit_failed: "Failure",
    description: "Description",
    detect_fail_try_later: "Detection failed, please try again later",
    detected_you_are_using_steam: "You just logged in with Steam. In order to protect your account safety, we need to verify your mobile number.",
    detection_failed_please_try_again: "Detection failed, please try again later",
    detects_network_anomalies_please_try: "Network error, please try again later",
    detects_that_you_are_also: "You have not yet bound Steam, please bind first.",
    determine_the_selected_accessories_to: "Are you sure to unlist the selected items?",
    determined_to_be_removed_from: "Are you sure you want to cancel your collection?",
    do_not_exceed_24_characters: "Do not exceed 24 characters",
    edit_description: "Edit description",
    edit_the_description: "Edit description",
    enter_the_verification_code: "Enter the code",
    error_code: "Error code:",
    failure_to_modify: "Failure",
    feedback_success: "Success",
    for_the_protection_of_your: "In order to protect your account safety, we need to verify the Steam account bound to this account.",
    fraud_notice: "Beware of scams, please check if the API key was created? If it was maliciously created, please delete and change Steam password immediately.",
    listing_instructions_title: "Listing instructions",
    listing_instructions_message: " has a stacking situation, you can only list one of them. You can only continue to list the other parts after completing the transaction or removing it from the selling list.",
    listing_instructions_confirm: "Continue to list",
    deposit_instructions_title: "Deposit instructions",
    deposit_instructions_message: " has a stacking situation, so it will be treated as one item only when it is deposited into the BUFF backpack. Please set the quantity to 1 when depositing.",
    deposit_instructions_confirm: "Deposit",
    get_in: "Get in...",
    get_steam_trading_link: "Get trade url",
    get_the_package_deal_failed: "Failure",
    get_the_verification_code: "Get code",
    go_to_bind: "Bind",
    go_to_bind_card: "Bind",
    go_to_check: "Check",
    go_to_market: "View market",
    go_to_set: "Set",
    go_to_settings: "Set",
    go_to_verify: "Vefify",
    go_to_view: "View",
    greater_than_the_extraction_amount: "Greater than the amount available",
    has_been_sent: "Has been sent",
    has_been_used: "Has been used",
    hour: "hour",
    hours: "hours",
    i_first_look_at_the: "Have a look",
    i_know: "I know",
    i_think_again: "Think again",
    id_card_number_errors_please: "The ID number is wrong, please re-enter",
    id_number_can_not_be: "ID number cannot be empty",
    in_order_to_your_funds: "For your account safety, please fill in the following information",
    input_content_too_long_to_40_words: "The input is too long, please less than 40 words",
    instrongmy_counterofferstrongattention_counteroffer_status_the: 'After the seller accepts the bargain and send offer, you need go to <strong>Buy History</strong> to accept the offer. or the <strong class="c_Yellow">2%</strong> bargain amount will be deducted to the seller as a compensation.',
    is_being_processed_you_can: "Being processed, you can check the latest progress in withdrawal records.",
    is_being_uploaded: "Uploading...",
    it_detects_your_steam_account: "Your steam account looks good to trade.",
    it_is_determined_to_cancel: "Are you sure to cancel the delivery?",
    items_on_the_shelves_successful: "Success",
    jewelry: "item",
    less_than: "less than",
    login: "Login",
    member: "piece",
    pluar_s: "s",
    minimum_price_can_not_be: "The min price can't be higher than the max price",
    minute: "minute",
    minutes: "minutes",
    modify_the_price: "Change price",
    modify_the_success: "Success",
    nickname_modify_too_frequently_notice: "Change too often, please change after {{time}}",
    need_to_first_agree_to: "Agree to the payment agreement first",
    network_error: "Network error, please try again later",
    network_request_failed: "Network request failed",
    next_page: "Next page",
    no_available_items: "No available items",
    no_longer_prompt: "Do not remind again",
    no_meet_the_requirements_of: "No items meet the requirement",
    no_related: "No related items",
    not_found_to_contain_the: "Search result is empty",
    not_my_phone_number_please: "Not my phone number? please",
    not_support_credit_card: "Credit card is not supported",
    number: "Number：",
    quantity: "Quantity：",
    of_buying_ityuan: "purchase？￥",
    off_the_shelves_results: "Result",
    ok: "OK",
    on_frame_failure: "Failure",
    out_collection: "Cancel collection",
    package_deal: "Package trade",
    packaged_transaction_within_the_test: "This function is not available.",
    page_size: "Number per page",
    page_temporarily_does_not_support: "The webpage does not support bulk buy. Please go to BUFF APP.",
    pattern_template: "Paint seed",
    pay_failed: "Payment failed",
    payment: "Paying",
    payment_system_is_busy_please: "The payment system is busy, please check the payment result in Buy History.",
    piece_of_goods: "items",
    piece_of_goods_please_go: "items，please check in Buy History",
    please_agree_to_the_service: "Please agree to the service agreement first.",
    please_be_patient: "please wait patiently",
    please_choose_to_be_a: "Please choose items",
    please_choose_to_be_on: "Please choose items",
    please_do_the_safety_confirmation: "Please confirm the security and enter",
    please_enter: "Please enter&nbsp;",
    please_enter_image_verification_code: "Please enter image verification code",
    please_enter_or_select_the: "Please enter or select a top up amount\\n",
    please_enter_pricing: "Please enter price",
    please_enter_the_account_password: "Enter password",
    please_enter_the_auto_logoff: "Please enter the auto offline time",
    please_enter_the_correct_invite: "Please enter the correct invitation code",
    please_enter_the_netease_mobile: "Enter mobile number",
    please_enter_the_question_content: "Please enter feedback content",
    please_enter_the_redemption_code: "Please enter the code",
    please_enter_the_registered_phone: "Please enter mobile phone",
    please_enter_the_sms_verification: "Enter code",
    please_enter_the_verification_code: "Enter code",
    please_enter_your_steam_trade: "Enter trade url",
    please_fill_out_the_trading: "Please fill in the trade url",
    please_get_a_sms_verification: "Please get the code first",
    please_get_a_verification_code: "Please get the code first",
    please_go_to_buff_the: "Please send offer in BUFF APP",
    please_go_to_my_sell: "Please deliver in My Sale",
    please_in_the_backpack_view: "Please check in backpack",
    please_input_01000_between_the: "Please enter a paint seed between 0-1000",
    please_input_the_correct_mailbox: "please enter your valid email",
    please_modify_the_nickname: "Please change your nickname",
    please_select_deposit_item: "Please choose items",
    please_select_from_the_available: "Please select an available coupon",
    please_select_item: "Please choose items",
    "please_select_recharge_way\\n": "Please select the top up method\\n",
    please_select_the_bank_account: "Please select bank account",
    "please_select_the_card\\n": "Please select bank card\\n",
    please_select_the_you_want: "Please choose items",
    please_select_to_ship_the: "Please choose items",
    please_tick_the_below_statement: "Please tick the statement below",
    please_upload_picture: "Please upload an image",
    please_wait: "Please wait...",
    please_wait_for_seller_to: "Please wait for the seller to send offer and accept it",
    please_wait_for_the_seller: "Please wait for seller to send offer. After that, you need to accept offer",
    please_wait_patiently_have_been: "Please be patient, have waited",
    pmost_can_only_be_bound: "<p>Can only be bound at most",
    press_and_hold_the_slider: "Hold down the slider and drag to complete the puzzle above",
    prev_page: "Previous page",
    price_must_be_greater_than: "The price must be greater than: ",
    private_transaction_within_the_test: "This function is not available.",
    private_transactions: "Private trade",
    prompt: "Tip",
    purchase: "Buying",
    purchase_failed: "Failure",
    purchase_failure_reason_as_follows: "failed, reasons:",
    purchase_price_not_greater_than: "Purchase price cannot be greater than ",
    ranking_total_ranking: "Total rank",
    reacquire_the_print_data: "Re-acquire sticker data",
    receive_sms_verification_code: "&nbsp;SMS code received.",
    recharge_failed: "Failure",
    recharge_successful: "Success",
    recharge_with_cash_only_support: "Top up and withdrawal only support Debit card",
    recharge_yuan: "Top up ￥",
    recommended_use_of_the_netease: 'It is recommended to use the NetEase UU booster,<a href="/help#steam_network">查看更多解决方案</a>',
    refresh: "Refresh",
    refresh_in_the: "Refresh...",
    refreshing: "Refresh",
    register_a_new_account: "register new account",
    registration: "register",
    reminder: "Reminder",
    replicated: "Copied",
    reply_success: "Success",
    request: "Request in",
    require_minimal_packaging_of_two: "Need to pack at least two items",
    resend: "Resend",
    retrieval_failure: "Failed to retrieve",
    retrieve_the_process_description: "Retrieve process introduction",
    reupload: "Re-upload",
    sale_amount: "Sale amount",
    sale_amount_yuan: "Sale amount: ",
    sale_number_: "Sale number: ",
    save: "Save",
    seconds: "seconds",
    select_to_change_the_price: "Please choose items",
    select_to_retrieve_the_goods: "Please choose items",
    select_up_to_200_pieces: "Choose up to 200 items",
    send_a_verification_code_failed: "Send verification code failed",
    sent_successfully_please_note_the: "Successfully sent",
    set_success: "Success",
    set_the_boot: "Guide",
    set_to_fail: "Failure",
    set_up_steam_trade_url: "Set Steam trade url",
    set_up_trading_links: "Set trade url",
    settings_failed_please_try_again: "Failure",
    shelve_failed: "Failure",
    shelve_notice: "Please deliver within 12 hours after the buyer pays, otherwise the item will be removed from sale and your selling function will be banned.",
    shelve_success: "Success",
    shelves_successful: "Success",
    since_the_csgo_official_trading: 'Due to changes in the official trade rules of CS:GO, the items will not be retrieved within 7 days after depositing.<a href="/help#csgo_trade_cooldown" target="_blank">CS:GO交易机制改动</a>',
    skip_maybe_next_time: "Skip",
    sold_number_of_pieces: "Sale number",
    steam_trade_limit: "Your Steam account cannot trade at the moment. Please check steam help.",
    successful_supply: "Success",
    successful_upload: "Success",
    successfully_submitted: "Success",
    supply_failure: "Failure",
    supply_success: "Success",
    sure_you_want_to_delete: "Are you sure you want to delete this card??",
    system_busy_error: "The system is busy, please try again later",
    termination_buying: "Cancel purchase",
    the_account_can_be_withdrawal: "Unable to withdraw, insufficient balance in the BUFF Balance-Other",
    the_amount_of_recharge_need: "The amount needs to be a number",
    the_authentication_is_successful: "Success",
    the_bank_card_number_can: "Bank card number cannot be empty",
    the_bank_card_number_errors: "Bank card number is wrong, please re-enter",
    the_binding_is_successful: "Success",
    the_content_of_the_input: "The input is too long, please less than 40 words",
    the_current_balance_of_dollar: ", current balance ￥",
    the_current_page_is_no: "No items",
    the_degree_of_wear_get: "Acquiring...",
    the_goods_can_not_a: "The item cannot be priced automatically , please enter it",
    the_goods_is_not_buying: "This item is not available for purchase.",
    the_lack_of_balance: "Insufficient balance",
    the_maximum_allowable_amount_of: "The maximum allowable top up amount is",
    the_minimum_allowable_amount_of: "The minimum allowable top up amount is",
    the_modified_price_of_success: "Success",
    the_payment_is_successful: "Success",
    the_phone_number_cannot_be: "Phone number can not be empty",
    the_phone_number_has_been: "Has the phone number been changed? please",
    the_phone_number_is_incorrect: "The phone number is wrong, please re-enter",
    the_phone_receives_the_verification: "Verification code received",
    the_picture_is_being_resolved: "Inspecting, please click to view later",
    the_price_can_not_be: "The price cannot be greater than: ",
    the_purchase_amount_can_not: "The quantity of bulk buy cannot exceed the quantity in sale that meet the conditions.",
    the_quote_failed_to_send: "Failure: ",
    the_real_name_can_not: "Real name can not be empty",
    the_recommended_bit_is_already: "Recommended position is full",
    the_set_of_recommended_items: "Recommend",
    the_shelves: "Unlist",
    the_shelves_after_the_goods: "Are you sure to unlist the selected items?",
    the_system_is_busy: "The system is busy",
    the_system_is_busy_please: "The system is busy, please check in buy history",
    the_system_is_busy_you: "The system is busy, you can check the latest progress of the recharge in the recharge record.",
    the_system_is_busyplease_try: "The system is busy, please try again later",
    the_system_supports_the_maximum: "The system supports a maximum of 64 characters.",
    the_validation_is_successful: "Success",
    the_verification_code_is_incorrect: "Incorrect verification code",
    there_goods_is_not_input: "There are items not priced",
    tied_the_card_fails_please: "Failed. Please confirm that the information you entered is correct.",
    to_bind: "Bind",
    to_check: "Check",
    to_guarantee_your_safety_of: "Enter your mobile number",
    to_obtain_the_dynamic_code: "Failure",
    to_receive_the_success: "Success",
    to_shipping: "Deliver",
    to_steam: "Connect Steam",
    trade_url_setting_successful: "Success",
    trading_link_format_error: "Trade url format error",
    unbound_steam: "Unbound Steam",
    unbound_steam_notice: "You have not yet bound Steam, please bind first.",
    unbound_steam_trading_link_whether: "Unbound Steam trade url, please set first?",
    undelivered_notice: "Since you failed to deliver it last time, you will not be able to sell within {{hours}} hours {{minutes}} minutes.",
    unset_price_item: "There are items not priced",
    up_to_200_items: "Choose up to 200 items",
    "upload_success!_your_players_show": "Uploaded successfully! Your skins show is under review",
    user_login: "Login/Register",
    user_registration: "Register",
    valuation: "Valuation：",
    verification_code_cannot_be_empty: "verification code must be filled",
    verify: "Verify",
    view_a_player_show_please: "Please log in first",
    view_history_please_login: "Please log in first",
    view_more: "View more",
    view_more_long_time_of: "To view longer-term price trend, please exchange Observer.",
    view_more_long_time_of_for_premium: "You can join BUFF Plus to see the price trend for 6 months.",
    view_more_long_time_exchange: "To exchange",
    view_my_steam_inventory: "View my Steam inventory",
    view_price_trends_please_login: "Please log in first",
    view_top_bookmarked_please_login: "Please log in first",
    view_wear_ranking_please_log: "Please log in first",
    waiting_for_payment: "wait for payment",
    whether_the_problem_has_been: "Problem resolved?",
    whether_to_terminate_the_purchase: "Whether to terminate the current progress as {{progress}}? {{money}} will return your account balance",
    withdraw_cash_price_of_dollar: "Withdraw￥",
    withdraw_the_maximum_amount_of: "The maximum amount of withdrawal is",
    withdrawal_failure: "Failure",
    withdrawal_has_been_filed: "Has applied for withdrawal",
    withdrawal_minimum_amount_is: "The minimum amount to withdraw is",
    years: "years",
    you_can_recharge_in_a: "You can check the latest progress in the top-up record.",
    you_have_new_orders_need: "You have a new order to deliver.",
    you_have_yet_to_bind: "You have not yet bound the Steam trade url, please go to set",
    you_havent_successfully_paid_the: "You have not paid successfully, the order will be kept in buy history for 3 minutes, please pay as soon as possible.",
    you_must_be_over_18: "You must be at least 18 years old to use our service.",
    your_buying_price_is_higher: "Your purchase price is higher than the sale price, you may buy items higher than the market price, confirm?",
    your_current_steam_account_cant: "Your current Steam account cannot be traded. Please check our help documentation.",
    your_mobile_phone_account_occurs: "Your mobile account has been changed. In order to protect account safety, we need to verify your mobile account.",
    urs_password_login_need_verify: "In order to protect account safety, we need to verify your mobile account.",
    your_phone_account_through_a: "Your mobile account has changed and we need to verify your bound Steam account.",
    your_steam_account_halt: "Detected that your Steam account is in trade hold",
    your_steam_account_tradable: "Your Steam account looks good to trade.",
    your_steam_acctoun_trade_limit: "Your Steam account is unable to trade",
    your_steam_trade_url_invalid: "Your trade url has expired, please fetch it from Steam",
    yuan: "Yuan",
    some_etc: "{{count}} items",
    buying_num: "{{num}} demand",
    selling_num: "{{num}} on sale",
    inspecting: "Inspecting, please try again later",
    platform_name: "BUFF163 Skins marketplace",
    slogan: "Support games like CS:GO, DOTA2, etc.",
    download: "Download",
    check_sticker_wear_in_detail: "You can check whether the stickers are scratched at the bottom of the item page, please confirm before buying",
    get_code: "Get code",
    login_with_password: "Login with password",
    login_with_sms: "Login with SMS",
    login_register: "Login/Register",
    please_agree: "Please check the agreements first.",
    gift_card_buy_success: "Success! Share the gift card redemption code with the recipient, and you can also check it in My Coupon.<br>Recipient nickname: {{nickname}}<br>Redemption code: {{sn}}",
    gift_card_receiver_nickname_error: "BUFF nickname does not exist",
    gift_card_receiver_info: "BUFF avatar and nickname",
    disable_sms_notification_alert: "You will no longer receive order SMS alerts after this feature is turned off, please keep an eye on the app push message and process your order promptly.",
    disable_antiscam: "System will no longer help you intercept fake offer, please be vigilant and be aware of hijack scams.",
    scratch_sticker_notice: "The seller needs to ensure that the sticker information is consistent with the inventory after listing on the market. Scraping the stickers before delivering will result in the account being banned.",
    reconfirm: "Reconfirm",
    continue_selling: "Continue",
    please_input_store_name: "Please enter the store name",
    have_not_modify_store_name: "You have not modified the store name",
    determine_use_store_name_coupon: "This rename needs to consume 1 store rename coupon, are you sure to change it?",
    please_exchange_store_name_coupon_at_app: "Please exchange store rename coupon in BUFF APP",
    must_allow_epay_or_alipay: "You must accept one of Alipay and Wechat payment",
    cms_inspect_success_title: "inspect in server",
    cms_inspect_success_message: "CSGO game client will be launched to connect to the server for inspecting. The function is forbidden to be used for other purposes except inspecting before buying items. A 10-minute inspection time per day is provided during the beta test. ",
    buy_order_min_price: "Not less than {{min_price}}",
    premium_buy_success: "Purchase Premium Successfully",
    premium_buy_fail: "Purchase failed, please try again later",
    premium_will_expire_content: "Your membership is about to expire on {{date}}. You will lost your membership benefits such as Exclusive Identifier, Inspect in Server and Extra Listing Limit.",
    premium_expired_content: "Your membership has expired on {{date}}. To update your benefits, you can renew your membership.",
    premium_expired_renew_now: "Renew now",
    premium_waiting_for_payment: "wait for payment",
    premium_havent_successfully_paid: "you have not yet paid successfully, please pay as soon as possible.",
    premium_continue_to_pay: "Continue to pay",
    premium_confirm_leave: "Leave",
    user_asset_admin_frozen_notification: "Some balances have been frozen due to abnormal operation of the account, please submit feedback.",
    remain_withdrawal_count_today: "Number of withdrawal remains today:",
    please_choose_coupon: "Coupon",
    not_use_coupon: "Do not use",
    expired_coupon_switch: "The coupon has expired and will be voided if replaced or cancelled.",
    no_coupon_to_use: "No coupon",
    notes: "Notes",
    notes_exceed_max_len: "Add no more than 40 characters. This is not item description and can only be seen by yourself.",
    purchased: " Purchased",
    submitted: "Submitted",
    edit_notes: "Edit Notes",
    add_notes: "Add Notes",
    notes_desc: "Notes(Private):"
});
i18nData.updateData("zh", {
    "1_seconds": "1秒",
    _piece_of_goods_has: " 件饰品已被买家购买支付中，下架失败</p>",
    _piece_of_goods_off: " 件饰品下架成功</p>",
    a_period_of_time_: "一段时间: ",
    a_picture_is_not_uploaded: "有图片未上传成功",
    a_successful_purchase: "成功购买",
    access_to_the_steam_encounters: "访问Steam遇到问题？",
    account_can_be_withdraw_the: "账户内可提现的BUFF余额-其他不足，无法提现",
    acknowledgment_is_bound_to_the: "确认绑定到这个Steam帐号吗？<br>Steam昵称：",
    acquisition_fee_failed_please_try: "获取手续费失败，请稍后再试",
    add_a_description: "添加描述",
    add_description: "添加描述",
    add_in_5_minutes_to: "请在5分钟内前往网易BUFF APP购买记录发送报价",
    add_in_the_buyers_payment: "请在买家付款后12小时内手动发货，否则系统将下架该类饰品并扣除信用值",
    add_the_other_card: "添加其他银行卡",
    all: "全选",
    already_have_an_account_click: "已有帐号？点这里登录",
    analysis: "解析中",
    analysis_figure: "解析图",
    api_key_format_error: "API key格式错误",
    api_key_successfully_set: "API key设置成功",
    application_authentication_failure_please_contact: "申请认证失败，请联系客服人员",
    artificial_assist: "人工协助",
    authentication: "身份验证",
    back_for_refresh: "再回到当前页面点击刷新按钮",
    backpack_capacity_is_insufficient_can: "背包容量不足，无法继续购买",
    bargain_price_must_be_lower: "还价价格必须低于饰品在售价格",
    being_prepaid_in: "正在充值中",
    beware_of_phishing_scams_please: "慎防钓鱼诈骗，请先检查Steam账号是否被创建API key！如发现被恶意创建，请马上删除并更改密码。",
    binding_acknowledgment: "绑定确认",
    binding_steam: "绑定Steam",
    binding_steam_before_you_can: "绑定Steam后才可以使用BUFF账号拥有更多权限。",
    binding_transaction_link_the_immediate: "绑定交易链接，立即体验BUFF交易",
    bound_to_fail: "绑定失败",
    buff_backpack_capacity_is_insufficient: "BUFF背包容量不足，已调整为可购买最大数量",
    buy_price_cannot_be_less: "求购价格不能小于0.01",
    buy_pubgrecycled_transactionitems_not_get: "购买PUBG(回收交易)的物品无法取回到游戏中，需要等待PUBG游戏官方开放个人交易才可取回。",
    buy_success: "购买成功",
    buying_in_bulk_quantity_can: "批量购买数量不能超过",
    buying_in_bulk_results: "批量购买结果",
    can_not_supply_your_own: "不能供应自己求购的物品",
    cancel: "取消",
    cancel_buying_success: "取消求购成功",
    cancel_delivery_success: "取消发货成功",
    cancel_recommend: "取消推荐",
    cancel_the_shipment: "取消发货",
    cannot_be_resolved_the_goods: "无法解析，该饰品已被出售或网络不好",
    cannot_purchase_your_own_items: "不能购买自己出售的物品",
    card_limit_is_reached: "银行卡达到上限",
    cardsp: "张银行卡</p>",
    century: "世纪",
    change_price_of_failure: "改价失败",
    clear_the_api_key_after: "清除API key后，你的店铺将离线，自售中的饰品将无法被购买。确定要清除吗？",
    click_on_upload_picture: "点击上传图片",
    click_to_collapse: "点击收起",
    click_to_expand: "点击展开",
    close_failed_please_try_again: "关闭失败，请重试",
    complete: "完成",
    confirm: "确认",
    confirm_and_opened: "确认并开通",
    confirm_clear: "确认清除",
    confirm_leave: "确认离开",
    confirm_to_cancel_the_transaction: "确认取消交易",
    confirmation_of_payment: "确认付款",
    "congratulations_to_you!_welcome_to": "恭喜您！欢迎来到BUFF，您可以立马开始交易了！",
    consignment_goods_shelf_will_be: "寄售饰品下架后将返回你的BUFF背包。",
    content_length_can_not_be: "内容长度不能大约1024个字符",
    continue_to_pay: "继续支付",
    counteroffer_price_cannot_be_lower: "还价价格不能低于饰品的最低出价",
    counteroffer_request_has_been_sent: "还价请求已发送",
    create_a_package_of_trading: "创建打包交易成功",
    create_buying_success: "创建求购成功",
    csgo_deposit_notice: '由于V社修改了饰品交易规则，该饰品购买后需要7天才能再次交易，详情查看<a href="/help#csgo_trade_cooldown" target="_blank">CSGO/DOTA2交易机制改动</a>',
    currently_does_not_support_the: "目前不支持该卡号，请更换卡号",
    currently_have_to_wait_for: "当前已有等待客服处理的反馈，如果还需反馈，请前往补充",
    day: "天",
    days: "天",
    delete_confirmation: "删除确认",
    delete_failed: "删除失败",
    delivery_prompt: "发货提示",
    delivery_timeout: "发货超时",
    deposit_backpack: "存入背包",
    deposit_failed: "存入失败",
    description: "说明",
    detect_fail_try_later: "检测失败，请稍后再试",
    detected_you_are_using_steam: "检测到你是用Steam登录，为了保障帐号财产安全，需要验证手机帐号。",
    detection_failed_please_try_again: "检测失败，请稍后再试",
    detects_network_anomalies_please_try: "检测到网络异常，请稍后再试",
    detects_that_you_are_also: "检测到您还未绑定Steam，继续操作前请先完成Steam账号绑定",
    determine_the_selected_accessories_to: "确定将选中的饰品下架？",
    determined_to_be_removed_from: "确定要移出收藏吗？",
    do_not_exceed_24_characters: "不要超过24个字符",
    edit_description: "编辑描述",
    edit_the_description: "编辑描述",
    enter_the_verification_code: "输入验证码",
    error_code: "错误码：",
    failure_to_modify: "修改失败",
    feedback_success: "反馈成功",
    for_the_protection_of_your: "为保障你的帐号资产安全，需要验证该帐号绑定的Steam帐号",
    fraud_notice: "慎防钓鱼诈骗，请先检查Steam账号是否被创建API key！如发现被恶意创建，请马上删除并更改密码。",
    listing_instructions_title: "上架须知",
    listing_instructions_message: "存在堆叠情况，你只能上架其中的一件。完成交易或下架后，才能继续上架其他部分。",
    listing_instructions_confirm: "继续上架",
    deposit_instructions_title: "存入须知",
    deposit_instructions_message: "存在堆叠情况，存入BUFF背包时仅视为一件处理。存入时请设置数量为1。",
    deposit_instructions_confirm: "继续存入",
    get_in: "获取中...",
    get_steam_trading_link: "获取Steam交易链接",
    get_the_package_deal_failed: "获取打包交易失败",
    get_the_verification_code: "获取验证码",
    go_to_bind: "前往绑定",
    go_to_bind_card: "去绑卡",
    go_to_check: "前往检查",
    go_to_market: "去市场看看",
    go_to_set: "前往设置",
    go_to_settings: "前往设置",
    go_to_verify: "去认证",
    go_to_view: "前往查看",
    greater_than_the_extraction_amount: "大于可提金额",
    has_been_sent: "已发送",
    has_been_used: "已使用",
    hour: "小时",
    hours: "小时",
    i_first_look_at_the: "我先看看",
    i_know: "我知道了",
    i_think_again: "我再想想",
    id_card_number_errors_please: "身份证号错误，请重新输入",
    id_number_can_not_be: "身份证号不能为空",
    in_order_to_your_funds: "为了您的资金和交易安全，请完善以下资料",
    input_content_too_long_to_40_words: "输入的内容太长，请少于40个字",
    instrongmy_counterofferstrongattention_counteroffer_status_the: '在<strong>我的还价</strong>关注还价状态，卖家接受还价并发起报价后，立即前往<strong>购买记录</strong>接受报价，超时未接受报价将扣除<strong class="c_Yellow">2%</strong>还价金额给卖家作为补偿。',
    is_being_processed_you_can: "正在处理中，你可以在提现记录中查看最新进度。",
    is_being_uploaded: "正在上传...",
    it_detects_your_steam_account: "检测到你的Steam账号可以正常交易了",
    it_is_determined_to_cancel: "确定取消发货吗？",
    items_on_the_shelves_successful: "物品上架成功",
    jewelry: "的饰品",
    less_than: "小于",
    login: "登录",
    member: "件",
    pluar_s: " ",
    minimum_price_can_not_be: "最低价不能高于最高价",
    minute: "分",
    minutes: "分钟",
    modify_the_price: "修改价格",
    modify_the_success: "修改成功",
    nickname_modify_too_frequently_notice: "修改太频繁，请{{time}}后再修改",
    need_to_first_agree_to: "需要先同意支付协议",
    network_error: "检测到网络异常，请稍后再试",
    network_request_failed: "网络请求失败",
    next_page: "下一页",
    no_available_items: "当前页无可选择上架或存入的饰品",
    no_longer_prompt: "不再提示",
    no_meet_the_requirements_of: "暂无符合要求的饰品",
    no_related: "暂无相关饰品",
    not_found_to_contain_the: "没有搜到包含关键词",
    not_my_phone_number_please: "不是本人的手机号？请寻求",
    not_support_credit_card: "暂不支持信用卡",
    number: "件数：",
    quantity: "件数：",
    of_buying_ityuan: "的求购？￥",
    off_the_shelves_results: "下架结果",
    ok: "确定",
    on_frame_failure: "上架失败",
    out_collection: "移出收藏",
    package_deal: "打包交易",
    packaged_transaction_within_the_test: "打包交易内测中，敬请期待",
    page_size: "每页显示数",
    page_temporarily_does_not_support: "网页暂不支持批量购买，请前往APP操作，支持合并报价更便捷。",
    pattern_template: "图案模板",
    pay_failed: "支付失败",
    payment: "支付中",
    payment_system_is_busy_please: "支付系统繁忙，请在购买记录查看支付结果。",
    piece_of_goods: "件饰品",
    piece_of_goods_please_go: "件饰品，请到购买记录中查看",
    please_agree_to_the_service: "请先同意服务协议",
    please_be_patient: "请耐心等待",
    please_choose_to_be_a: "请选择要私密交易的物品",
    please_choose_to_be_on: "请选择要上架的物品",
    please_do_the_safety_confirmation: "请进行安全确认，输入",
    please_enter: "请输入",
    please_enter_image_verification_code: "请输入图片验证码",
    please_enter_or_select_the: "请输入或选择充值金额\\n",
    please_enter_pricing: "请输入定价",
    please_enter_the_account_password: "请输入帐号密码",
    please_enter_the_auto_logoff: "请输入自动下线时间",
    please_enter_the_correct_invite: "请输入正确的邀请码",
    please_enter_the_netease_mobile: "请输入网易手机帐号",
    please_enter_the_question_content: "请输入问题内容",
    please_enter_the_redemption_code: "请输入兑换码",
    please_enter_the_registered_phone: "请输入注册手机号",
    please_enter_the_sms_verification: "请输入短信验证码",
    please_enter_the_verification_code: "请输入验证码",
    please_enter_your_steam_trade: "请输入您的Steam交易链接",
    please_fill_out_the_trading: "请填写交易链接",
    please_get_a_sms_verification: "请先获取短信验证码",
    please_get_a_verification_code: "请先获取验证码",
    please_go_to_buff_the: "请前往BUFF APP发送报价",
    please_go_to_my_sell: "请前往我的出售发货",
    please_in_the_backpack_view: "请在背包中查看。",
    please_input_01000_between_the: "请输入0-1000之间的模板编号",
    please_input_the_correct_mailbox: "请输入正确的邮箱",
    please_modify_the_nickname: "请修改昵称",
    please_select_deposit_item: "请选择要存入的物品",
    please_select_from_the_available: "请选择可用的提现券",
    please_select_item: "请选择要上架的物品",
    "please_select_recharge_way\\n": "请选择充值方式\\n",
    please_select_the_bank_account: "请选择银行账户",
    "please_select_the_card\\n": "请选择银行卡\\n",
    please_select_the_you_want: "请选择要下架的物品",
    please_select_to_ship_the: "请选择要发货的饰品",
    please_tick_the_below_statement: "请先勾选下方声明",
    please_upload_picture: "请上传图片",
    please_wait: "请稍候...",
    please_wait_for_seller_to: "请等待卖家发起报价，后续需确认收货",
    please_wait_for_the_seller: "请等待卖家发货，可在购买记录查看进度。",
    please_wait_patiently_have_been: "请耐心等待，已等待",
    pmost_can_only_be_bound: "<p>最多只能绑定",
    press_and_hold_the_slider: "按住滑块，拖动完成上方拼图",
    prev_page: "上一页",
    price_must_be_greater_than: "价格必须大于:",
    private_transaction_within_the_test: "私密交易内测中，敬请期待",
    private_transactions: "私密交易",
    prompt: "提示",
    purchase: "购买中",
    purchase_failed: "购买失败",
    purchase_failure_reason_as_follows: "购买失败，原因如下：",
    purchase_price_not_greater_than: "求购价格不能大于",
    ranking_total_ranking: "排行总榜",
    reacquire_the_print_data: "重新获取印花数据中",
    receive_sms_verification_code: "收到的短信验证码。",
    recharge_failed: "充值失败",
    recharge_successful: "充值成功",
    recharge_with_cash_only_support: "充值与提现只支持储蓄卡",
    recharge_yuan: "充值 ￥",
    recommended_use_of_the_netease: '建议使用网易UU加速器，<a href="/help#steam_network">查看更多解决方案</a>',
    refresh: "刷新",
    refresh_in_the: "刷新中...",
    refreshing: "刷新中",
    register_a_new_account: "注册新帐号",
    registration: "注册",
    reminder: "温馨提醒",
    replicated: "已复制",
    reply_success: "回复成功",
    request: "请求中",
    require_minimal_packaging_of_two: "需要最少打包两件饰品",
    resend: "重新发送",
    retrieval_failure: "取回失败",
    retrieve_the_process_description: "取回流程简介",
    reupload: "重新上传",
    sale_amount: "出售金额",
    sale_amount_yuan: "出售金额: ",
    sale_number_: "出售数量: ",
    save: "保存",
    seconds: "秒",
    select_to_change_the_price: "请选择要改价的物品",
    select_to_retrieve_the_goods: "请选择要取回的饰品",
    select_up_to_200_pieces: "最多选择200件饰品",
    send_a_verification_code_failed: "发送验证码失败",
    sent_successfully_please_note_the: "发送成功，请留意手机短信",
    set_success: "设置成功",
    set_the_boot: "设置引导",
    set_to_fail: "设置失败：",
    set_up_steam_trade_url: "设置Steam交易链接",
    set_up_trading_links: "设置交易链接",
    settings_failed_please_try_again: "设置失败，请稍后再试",
    shelve_failed: "上架失败",
    shelve_notice: "请在买家付款后12小时内发货，否则系统将下架该类饰品并扣除信用值",
    shelve_success: "上架成功",
    shelves_successful: "下架成功",
    since_the_csgo_official_trading: '由于 CS:GO 官方交易规则改动，该饰品购买后需要7天后才能取回，详情查看<a href="/help#csgo_trade_cooldown" target="_blank">CS:GO交易机制改动</a>',
    skip_maybe_next_time: "跳过，下次再说",
    sold_number_of_pieces: "出售件数",
    steam_trade_limit: "你当前Steam帐号无法交易，请查看我们的帮助文档",
    successful_supply: "成功供应",
    successful_upload: "上传成功",
    successfully_submitted: "提交成功",
    supply_failure: "供应失败",
    supply_success: "供应成功",
    sure_you_want_to_delete: "确定要删除该银行卡吗?",
    system_busy_error: "系统繁忙，请稍后再试",
    termination_buying: "终止求购",
    the_account_can_be_withdrawal: "帐户内可提现的BUFF余额-支付宝不足，无法提现",
    the_amount_of_recharge_need: "充值金额需要是数字",
    the_authentication_is_successful: "认证成功",
    the_bank_card_number_can: "银行卡号不能为空",
    the_bank_card_number_errors: "银行卡号错误, 请重新输入",
    the_binding_is_successful: "绑定成功",
    the_content_of_the_input: "输入的内容太长，请少于40个字",
    the_current_balance_of_dollar: "，当前余额 ￥",
    the_current_page_is_no: "当前页无可选择上架或取回的饰品",
    the_degree_of_wear_get: "磨损度获取中...",
    the_goods_can_not_a: "该饰品无法一键定价，请手动输入",
    the_goods_is_not_buying: "该饰品不可求购",
    the_lack_of_balance: "余额不足",
    the_maximum_allowable_amount_of: "最大允许充值金额是",
    the_minimum_allowable_amount_of: "最小允许充值金额是",
    the_modified_price_of_success: "改价成功",
    the_payment_is_successful: "支付成功",
    the_phone_number_cannot_be: "手机号码不能为空",
    the_phone_number_has_been: "手机号已更换？请寻求",
    the_phone_number_is_incorrect: "手机号码错误，请重新输入",
    the_phone_receives_the_verification: "手机收到的验证码",
    the_picture_is_being_resolved: "图片正在解析中，请稍后点击查看",
    the_price_can_not_be: "价格不能大于:",
    the_purchase_amount_can_not: "购买数量不能超过满足条件的在售数量",
    the_quote_failed_to_send: "报价发送失败: ",
    the_real_name_can_not: "真实姓名不能为空",
    the_recommended_bit_is_already: "推荐位已满",
    the_set_of_recommended_items: "设为推荐项",
    the_shelves: "下架",
    the_shelves_after_the_goods: "下架后，饰品将返回你的BUFF背包。确定要取消",
    the_system_is_busy: "系统繁忙",
    the_system_is_busy_please: "系统繁忙，请前往购买记录查看",
    the_system_is_busy_you: "系统繁忙，你可以在充值记录中查看该笔充值的最新进度",
    the_system_is_busyplease_try: "系统繁忙,请稍候再试",
    the_system_supports_the_maximum: "系统支持最长姓名为64个字",
    the_validation_is_successful: "验证成功",
    the_verification_code_is_incorrect: "验证码不正确",
    there_goods_is_not_input: "有饰品未输入定价",
    tied_the_card_fails_please: "绑卡失败，请确认你输入的信息无误",
    to_bind: "前往绑定",
    to_check: "前往检查",
    to_guarantee_your_safety_of: "为保障你的资金安全，提现操作需要验证手机短信，请输入BUFF帐号绑定的手机号码",
    to_obtain_the_dynamic_code: "获取动态验证码失败",
    to_receive_the_success: "领取成功",
    to_shipping: "前往发货",
    to_steam: "前往Steam",
    trade_url_setting_successful: "交易URL设置成功",
    trading_link_format_error: "交易链接格式错误",
    unbound_steam: "未绑定Steam",
    unbound_steam_notice: "检测到您还未绑定Steam，继续操作前请先完成Steam账号绑定",
    unbound_steam_trading_link_whether: "未绑定Steam交易链接，是否前往设置？",
    undelivered_notice: "由于你上一次交易未能成功发货，无法上架该类物品还剩：{{hours}}小时{{minutes}}分",
    unset_price_item: "有饰品未输入定价",
    up_to_200_items: "最多选择200件饰品",
    "upload_success!_your_players_show": "上传成功！你的玩家秀正在审核中",
    user_login: "登录/注册",
    user_registration: "用户注册",
    valuation: "估值：",
    verification_code_cannot_be_empty: "验证码不能为空",
    verify: "验证",
    view_a_player_show_please: "查看玩家秀请先登录BUFF",
    view_history_please_login: "查看成交记录请先登录BUFF",
    view_more: "查看更多",
    view_more_long_time_of: '使用积分兑换"价格走势侦察"，查看更长时间饰品价格趋势。',
    view_more_long_time_of_for_premium: "查看6个月的价格趋势，请前往会员页面开通。",
    view_more_long_time_exchange: "前往",
    view_my_steam_inventory: "查看我的Steam库存",
    view_price_trends_please_login: "查看价格趋势请先登录BUFF",
    view_top_bookmarked_please_login: "查看热门关注请先登录BUFF",
    view_wear_ranking_please_log: "查看磨损排行请先登录BUFF",
    waiting_for_payment: "等待支付",
    whether_the_problem_has_been: "是否问题已解决？",
    whether_to_terminate_the_purchase: "是否终止当前进度为{{progress}}的求购？{{money}}将退回你的账户余额",
    withdraw_cash_price_of_dollar: "提现￥",
    withdraw_the_maximum_amount_of: "提现的最高金额为",
    withdrawal_failure: "提现失败",
    withdrawal_has_been_filed: "提现已申请",
    withdrawal_minimum_amount_is: "提现的最低金额为",
    years: "年",
    you_can_recharge_in_a: "你可以在充值记录中查看最新进度。",
    you_have_new_orders_need: "你有新的订单需要发货",
    you_have_yet_to_bind: "你尚未绑定Steam交易链接，请前往设置",
    you_havent_successfully_paid_the: "你还没有支付成功，订单会在我的购买记录保留三分钟，请尽快支付。",
    you_must_be_over_18: "你必须年满18岁才能使用我们的服务。",
    your_buying_price_is_higher: "你的求购价格高于在售价格，可能会买到高于市场价的饰品，确认要付款吗？",
    your_current_steam_account_cant: "你当前Steam帐号无法交易，请查看我们的帮助文档",
    your_mobile_phone_account_occurs: "你的手机帐号发生过换号操作，为了保障帐号财产安全，需要验证手机帐号",
    urs_password_login_need_verify: "为了保障帐号财产安全，需要验证手机帐号",
    your_phone_account_through_a: "您的手机帐号发生过换号操作，需要验证绑定的Steam帐号",
    your_steam_account_halt: "检测到你的Steam账号处于交易暂挂期",
    your_steam_account_tradable: "检测到你的Steam账号可以正常交易了",
    your_steam_acctoun_trade_limit: "检测到你的Steam账号交易受限",
    your_steam_trade_url_invalid: "你的交易链接已经失效，请前往Steam重新获取",
    yuan: "元",
    some_etc: "等{{count}}件饰品",
    buying_num: "{{num}}件需求",
    selling_num: "{{num}}件在售",
    inspecting: "正在解析中，请稍后重试",
    platform_name: "网易BUFF饰品交易平台",
    slogan: "支持DOTA2，CSGO等热门游戏",
    download: "下载",
    check_sticker_wear_in_detail: "印花磨损可在详情页下拉查看，购买前请先确认",
    get_code: "获取验证码",
    login_with_password: "使用密码验证登录",
    login_with_sms: "使用短信验证登录",
    login_register: "登录/注册",
    please_agree: "请先同意用户协议和隐私政策",
    gift_card_buy_success: "成功购买礼品卡！快将礼品卡兑换码分享给获赠人吧，你也可以在我的卡券中查看。<br>获赠人BUFF昵称：{{nickname}}<br>礼品卡兑换码：{{sn}}",
    gift_card_receiver_nickname_error: "BUFF昵称不存在，请检查是否正确",
    gift_card_receiver_info: "该用户BUFF头像与昵称",
    disable_sms_notification_alert: "关闭该功能后你将不再收到交易短信提醒，请留意APP推送信息并及时处理订单。",
    disable_antiscam: "系统将不再为你拦截仿冒交易报价，敬请提高警惕，谨防交易被劫持诈骗。",
    scratch_sticker_notice: "卖家需要确保上架后饰品印花信息与库存一致，发货前刮印花的行为会导致帐号被封禁。",
    reconfirm: "重新确认",
    continue_selling: "继续上架",
    please_input_store_name: "请输入店铺名称",
    have_not_modify_store_name: "您尚未修改店铺名称",
    determine_use_store_name_coupon: "本次改名需要消耗1张店铺改名券，是否确定修改？",
    please_exchange_store_name_coupon_at_app: "请前往BUFF APP兑换店铺改名券",
    must_allow_epay_or_alipay: "必须接受支付宝付款或微信支付付款中的一个",
    cms_inspect_success_title: "检视须知",
    cms_inspect_success_message: "将打开CSGO客户端，连接服务器进行检视，该功能仅限购买前检视参考饰品外观信息，禁止用于其他用途，如需使用饰品请购买在售饰品。因服务器负载量有限，内测期间提供单日10分钟的检视时长，如果连接失败，请检查CSGO客户端登录的Steam账号与BUFF绑定的是否一致。</br>如需使用蒸汽平台检视，可在账号设置中修改。",
    buy_order_min_price: "最低 {{min_price}}",
    premium_buy_success: "开通会员成功",
    premium_buy_fail: "开通失败，请稍后再试",
    premium_will_expire_content: "会员将于{{date}}过期，过期后将失去会员标识、社区服检视、上架数量扩容等特权，可前往网页续费。",
    premium_expired_content: "会员已于{{date}}过期，继续享受会员特权可前往网页续费。",
    premium_expired_renew_now: "前往续费",
    premium_waiting_for_payment: "等待支付",
    premium_havent_successfully_paid: "你还没有支付成功，请尽快支付。",
    premium_continue_to_pay: "继续支付",
    premium_confirm_leave: "确认离开",
    user_asset_admin_frozen_notification: "账户存在异常操作，部分资金已锁定，如有疑问，请联系客服。",
    remain_withdrawal_count_today: "今天剩余提现次数：",
    please_choose_coupon: "选择优惠券",
    not_use_coupon: "不使用",
    expired_coupon_switch: "该折扣券已过期，若替换或取消使用将作废。",
    no_coupon_to_use: "暂无可用",
    notes: "备注",
    notes_exceed_max_len: "添加不超过40字备注。备注非商品描述，仅自己可见。",
    purchased: "购入",
    submitted: "修改成功",
    edit_notes: "编辑备注",
    add_notes: "添加备注",
    notes_desc: "备注（仅自己可见）："
});
var renderGameNotification = function(data) {
    var games = {};
    ["to_accept_offer_order", "to_deliver_order", "to_handle_bargain", "to_pay_order", "to_receive_order"].forEach(function(key) {
        var item = data[key];
        for (var game in item) {
            games[game] = games[game] || 0;
            games[game] += item[game]
        }
    });
    var sum = 0;
    $("#j_game-switcher .j_drop img").each(function() {
        var count = games[$(this).attr("data-game")] || 0;
        var element = $(this).siblings(".tag_status");
        if (count > 0) {
            sum = sum + count;
            if (count > 99) {
                count = "99+"
            }
            element.show();
            element.text(count)
        } else {
            element.hide()
        }
    });
    if (sum > 0) {
        var element = $("#j_game-switcher h3 .tag_status");
        if (sum > 99) {
            sum = "99+"
        }
        element.show();
        element.text(sum)
    }
};
var notification = function() {
    var windowIsActive = true;
    var updateNotification = function(callback) {
        sendRequest("/api/message/notification", {
            method: "GET",
            showLoading: false,
            showError: false,
            success: function(data) {
                if (data.code == "OK") {
                    var my_backpack_count = 0;
                    var my_selling_count = 0;
                    var my_accepting_count = 0;
                    var my_bargain_count = 0;
                    var my_paying_count = 0;
                    if (data.data.to_send_offer_order) {
                        data.data.to_pay_order = data.data.to_pay_order || {};
                        for (var game in data.data.to_send_offer_order) {
                            data.data.to_pay_order[game] = (data.data.to_pay_order[game] || 0) + data.data.to_send_offer_order[game]
                        }
                    }
                    for (var item in data.data) {
                        if (item == "to_deliver_order") {
                            var deliver_game = "dota2";
                            var total_deliver_count = 0;
                            for (var game in data.data[item]) {
                                if (g.game != game) {
                                    continue
                                }
                                var count = data.data[item][game];
                                total_deliver_count += count;
                                if (count > 0) {
                                    deliver_game = game
                                }
                                my_selling_count += count;
                                if (count > 99) {
                                    count = "99+"
                                }
                                if ($(".to_deliver").hasClass("on")) {
                                    if (count > 0) {
                                        if ($(".tab-games a[data-game=" + game + "] span.tag_status").length > 0) {
                                            $(".tab-games a[data-game=" + game + "] span.tag_status").html(count)
                                        } else {
                                            $(".tab-games a[data-game=" + game + "]").append('<span class="tag_status">' + count + "</span>")
                                        }
                                        $(".tab-games a[data-game=" + game + "]").data("navpre", "/market/sell_order/to_deliver")
                                    } else {
                                        $(".tab-games a[data-game=" + game + "] span.tag_status").remove();
                                        $(".tab-games a[data-game=" + game + "]").data("navpre", "")
                                    }
                                }
                                if (count > 0 && $(".to_deliver a").length > 0 && $(".to_deliver a").attr("href").indexOf("game=" + game) != -1) {
                                    $(".to_deliver a").attr("href", "/market/sell_order/to_deliver?game=" + game)
                                }
                                if (count > 0 && $("#j_myselling a").attr("href").indexOf("game=" + game) != -1) {
                                    $("#j_myselling a").attr("href", "/market/sell_order/to_deliver?game=" + game)
                                }
                            }
                            if (my_selling_count > 0) {
                                if (my_selling_count > 99) {
                                    my_selling_count = "99+"
                                }
                                if ($(".cont-tab .to_deliver span.tag_status").length > 0) {
                                    $(".cont-tab .to_deliver span.tag_status").html(my_selling_count)
                                } else {
                                    $(".cont-tab .to_deliver").append('<span class="tag_status">' + my_selling_count + "</span>")
                                }
                            } else {
                                $(".cont-tab .to_deliver span.tag_status").remove()
                            }
                            $("#current-game-to-deliver").text(data.data[item][g.game]);
                            if (total_deliver_count > 0) {
                                var notification = {
                                    tag: "to_deliver_order_" + data.data.updated_at[item],
                                    title: i18n("delivery_prompt"),
                                    body: i18n("you_have_new_orders_need"),
                                    icon: "/static/images/favicon.ico",
                                    onclick: function() {
                                        window.open("/market/sell_order/to_deliver?game=" + deliver_game)
                                    }
                                };
                                sendNotification(notification)
                            }
                        } else if (item == "to_accept_offer_order") {
                            for (var game in data.data[item]) {
                                if (g.game != game) {
                                    continue
                                }
                                var count = data.data[item][game];
                                my_accepting_count += count;
                                if (count > 99) {
                                    count = "99+"
                                }
                                if ($(".to_accept_offer").hasClass("on")) {
                                    if (count > 0) {
                                        if ($(".tab-games a[data-game=" + game + "] span.tag_status").length > 0) {
                                            $(".tab-games a[data-game=" + game + "] span.tag_status").html(count)
                                        } else {
                                            $(".tab-games a[data-game=" + game + "]").append('<span class="tag_status">' + count + "</span>")
                                        }
                                    } else {
                                        $(".tab-games a[data-game=" + game + "] span.tag_status").remove()
                                    }
                                }
                            }
                            if (my_accepting_count > 0) {
                                if (my_accepting_count > 99) {
                                    my_accepting_count = "99+"
                                }
                                if ($(".cont-tab .to_accept_offer span.tag_status").length > 0) {
                                    $(".cont-tab .to_accept_offer span.tag_status").html(my_accepting_count)
                                } else {
                                    $(".cont-tab .to_accept_offer").append('<span class="tag_status">' + my_accepting_count + "</span>")
                                }
                            } else {
                                $(".cont-tab .to_accept_offer span.tag_status").remove()
                            }
                        } else if (item == "to_receive_order") {
                            for (var game in data.data[item]) {
                                if (g.game != game) {
                                    continue
                                }
                                var count = data.data[item][game];
                                my_backpack_count += count;
                                if (count > 99) {
                                    count = "99+"
                                }
                                if ($(".my_backpack").hasClass("on")) {
                                    if (count > 0) {
                                        if ($(".tab-games a[data-game=" + game + "] span.tag_status").length > 0) {
                                            $(".tab-games a[data-game=" + game + "] span.tag_status").html(count)
                                        } else {
                                            $(".tab-games a[data-game=" + game + "]").append('<span class="tag_status tag_status_get">' + count + "</span>")
                                        }
                                    } else {
                                        $(".tab-games a[data-game=" + game + "] span.tag_status").remove()
                                    }
                                }
                            }
                            if (my_backpack_count > 0) {
                                if (my_backpack_count > 99) {
                                    my_backpack_count = "99+"
                                }
                                var text = my_backpack_count;
                                if ($(".cont-tab .my_backpack span.tag_status").length > 0) {
                                    $(".cont-tab .my_backpack span.tag_status").html(text)
                                } else {
                                    $(".cont-tab .my_backpack").append('<span class="tag_status tag_status_get">' + text + "</span>")
                                }
                            } else {
                                $(".cont-tab .my_backpack span.tag_status").remove()
                            }
                        } else if (item == "to_handle_bargain") {
                            for (var game in data.data[item]) {
                                if (g.game != game) {
                                    continue
                                }
                                var count = data.data[item][game];
                                my_bargain_count += count;
                                if (count > 99) {
                                    count = "99+"
                                }
                                if ($(".to_handle_bargain").hasClass("on")) {
                                    if (count > 0) {
                                        if ($(".tab-games a[data-game=" + game + "] span.tag_status").length > 0) {
                                            $(".tab-games a[data-game=" + game + "] span.tag_status").html(count)
                                        } else {
                                            $(".tab-games a[data-game=" + game + "]").append('<span class="tag_status">' + count + "</span>")
                                        }
                                    } else {
                                        $(".tab-games a[data-game=" + game + "] span.tag_status").remove()
                                    }
                                }
                            }
                            if (my_bargain_count > 0) {
                                if (my_bargain_count > 99) {
                                    my_bargain_count = "99+"
                                }
                                if ($(".cont-tab .to_handle_bargain span.tag_status").length > 0) {
                                    $(".cont-tab .to_handle_bargain span.tag_status").html(my_bargain_count)
                                } else {
                                    $(".cont-tab .to_handle_bargain").append('<span class="tag_status">' + my_bargain_count + "</span>")
                                }
                            } else {
                                $(".cont-tab .to_handle_bargain span.tag_status").remove()
                            }
                        } else if (item == "to_pay_order") {
                            for (var game in data.data[item]) {
                                if (g.game != game) {
                                    continue
                                }
                                var count = data.data[item][game];
                                my_paying_count += count;
                                if (count > 99) {
                                    count = "99+"
                                }
                                if ($(".to_pay_order").hasClass("on")) {
                                    if (count > 0) {
                                        if ($(".tab-games a[data-game=" + game + "] span.tag_status").length > 0) {
                                            $(".tab-games a[data-game=" + game + "] span.tag_status").html(count)
                                        } else {
                                            $(".tab-games a[data-game=" + game + "]").append('<span class="tag_status">' + count + "</span>")
                                        }
                                    } else {
                                        $(".tab-games a[data-game=" + game + "] span.tag_status").remove()
                                    }
                                }
                            }
                            if (my_paying_count > 0) {
                                if (my_paying_count > 99) {
                                    my_paying_count = "99+"
                                }
                                if ($(".cont-tab .to_pay_order span.tag_status").length > 0) {
                                    $(".cont-tab .to_pay_order span.tag_status").html(my_paying_count)
                                } else {
                                    $(".cont-tab .to_pay_order").append('<span class="tag_status">' + my_paying_count + "</span>")
                                }
                            } else {
                                $(".cont-tab .to_pay_order span.tag_status").remove()
                            }
                        } else if (item == "unread_message" || item == "unread_system_message") {
                            if (data.data["unread_message"].total > 0 || data.data["unread_system_message"].total > 0) {
                                $(".floatbar .message-bar span.icon_new").show();
                                $(".my-menu .icon_menu_msg").siblings(".icon_new").show();
                                $(".nav .message .icon_new").show()
                            } else {
                                $(".floatbar .message-bar span.icon_new").hide();
                                $(".my-menu .icon_menu_msg").siblings(".icon_new").hide();
                                $(".nav .message .icon_new").hide()
                            }
                            if (data.data["unread_message"].total > 0) {
                                $("#j_mail-tab li[message_type=trade] .icon_new").css({
                                    display: "inline"
                                })
                            } else {
                                $("#j_mail-tab li[message_type=trade] .icon_new").hide()
                            }
                            if (data.data["unread_system_message"].total > 0) {
                                $("#j_mail-tab li[message_type=system] .icon_new").css({
                                    display: "inline"
                                })
                            } else {
                                $("#j_mail-tab li[message_type=system] .icon_new").hide()
                            }
                            if (data.data["unread_message"].total == 0 && data.data["unread_system_message"].total > 0) {
                                $(".floatbar .message-bar a").attr("href", "/user-center/message?type=system");
                                $(".my-menu .icon_menu_msg").parent().attr("href", "/user-center/message?type=system");
                                $(".nav .message a").attr("href", "/user-center/message?type=system")
                            } else {
                                $(".floatbar .message-bar a").attr("href", "/user-center/message?type=trade");
                                $(".my-menu .icon_menu_msg").parent().attr("href", "/user-center/message?type=trade");
                                $(".nav .message a").attr("href", "/user-center/message?type=trade")
                            }
                        } else if (item == "unread_feedback_replay") {
                            if (data.data[item].total > 0) {
                                $(".floatbar .feedback-bar span.icon_new").show()
                            } else {
                                $(".floatbar .feedback-bar span.icon_new").hide()
                            }
                        } else if (item == "new_roll_room") {
                            if (data.data[item].has_new) {
                                $("#roll-nav-bar .icon_new").show()
                            } else {
                                $("#roll-nav-bar .icon_new").hide()
                            }
                        }
                    }
                    if (my_backpack_count > 0 || my_accepting_count > 0 || my_paying_count > 0) {
                        $("#j_mybackpack .icon_new").show()
                    } else {
                        $("#j_mybackpack .icon_new").hide()
                    }
                    if (my_selling_count > 0 || my_bargain_count > 0) {
                        $("#j_myselling .icon_new").show()
                    } else {
                        $("#j_myselling .icon_new").hide()
                    }
                    renderGameNotification(data.data)
                }
                callback(data)
            }
        })
    };
    var startPolling = function() {
        updateNotification(function(data) {
            if (data.code == "OK" && windowIsActive == true) {
                setTimeout(startPolling, 10 * 1e3)
            }
        })
    };
    var closeNotice = function(noticeid, appid) {
        $("#notice-wrapper").remove();
        var r_ntcid = getCookie("r_ntcid");
        var appid_ntcid_dict = {};
        var appid_ntcid_list = [];
        if (r_ntcid) {
            var closed_appid_ntcid_list = r_ntcid.split(",");
            for (var i = 0; i < closed_appid_ntcid_list.length; i++) {
                var appid_ntcid = closed_appid_ntcid_list[i].split(":");
                if (appid_ntcid.length == 1) {
                    appid_ntcid_list.push(appid_ntcid[0])
                } else if (appid_ntcid.length == 2) {
                    appid_ntcid_dict[appid_ntcid[0]] = appid_ntcid[1]
                }
            }
        }
        if (!appid_ntcid_dict.hasOwnProperty(noticeid)) {
            appid_ntcid_dict[appid] = noticeid
        }
        var appids = Object.keys(appid_ntcid_dict);
        for (var i = 0; i < appids.length; i++) {
            appid_ntcid_list.push(appids[i] + ":" + appid_ntcid_dict[appids[i]])
        }
        document.cookie = "r_ntcid=" + appid_ntcid_list.join() + "; path=/"
    };
    var init = function() {
        $(window).blur(function() {
            windowIsActive = false
        });
        $(window).focus(function() {
            windowIsActive = true;
            startPolling()
        });
        updateNotification(function() {})
    };
    return {
        init: init,
        startPolling: startPolling,
        closeNotice: closeNotice
    }
}();
var tooltip = function() {
    var timer;
    var _timer;
    var _tooltip_cache = {};
    var current_show_id = null;
    var ele_params = {};
    var abortLast = function() {
        $(".tooltip-hover").remove();
        clearTimeout(timer)
    };
    var positionTool = function(ele_params, tooltip_id, html) {
        $("body").append(html);
        var left = ele_params.left;
        var width = $(window).width();
        var height = $(window).height();
        var tool_height = $("#" + tooltip_id).height();
        if (tool_height > height - 20) {
            tool_height = height - 20
        }
        var show_offset = {};
        if (left > width - left - ele_params.ele_width) {
            show_offset["left"] = left - $("#" + tooltip_id).width() - 10
        } else {
            show_offset["left"] = left + ele_params.ele_width + 10
        }
        if (ele_params.top + tool_height > height + window.pageYOffset) {
            show_offset["top"] = height + window.pageYOffset - tool_height - 10
        } else {
            show_offset["top"] = ele_params.top
        }
        show_offset["max-height"] = tool_height;
        $("#" + tooltip_id).css(show_offset);
        initCustomCurrency($("#" + tooltip_id))
    };
    var init = function() {
        $(document).on("mouseenter", "body .item-detail-img", function(event) {
            if ([570, 730, 440, 252490].indexOf($(this).data("appid")) < 0) {
                return
            }
            $(".tooltip-hover").remove();
            clearTimeout(_timer);
            ele_params = $(this).offset();
            ele_params.ele_width = $(this).width();
            var timeout = $(this).data("timeout") || 1e3;
            var classid = $(this).data("classid");
            var instanceid = $(this).data("instanceid");
            var steamid = $(this).data("steamid");
            var appid = $(this).data("appid");
            var sell_order_id = $(this).data("orderid");
            var origin = $(this).data("origin");
            var hide_refresh_sticker = $(this).hasClass("hide-refresh-sticker");
            var game = BuffConfig.SteamAPP.APPID_MAPS[appid];
            var data = {
                appid: appid,
                game: game,
                classid: classid,
                instanceid: instanceid,
                sell_order_id: sell_order_id,
                origin: origin || "null"
            };
            if (steamid) {
                data.steamid = steamid
            }
            var tooltip_id = "item-tooltip-" + appid + "-" + classid + "-" + instanceid;
            if ($(this).data("assetid")) {
                data["assetid"] = $(this).data("assetid");
                data["contextid"] = $(this).data("contextid");
                tooltip_id += "-" + data["assetid"]
            }
            tooltip_id += "-" + origin;
            current_show_id = tooltip_id;
            timer = setTimeout(function() {
                if (_tooltip_cache[tooltip_id] != undefined) {
                    positionTool(ele_params, tooltip_id, _tooltip_cache[tooltip_id], event);
                    bookmark().updateView()
                } else {
                    sendRequest("/market/item_detail", {
                        method: "GET",
                        showLoading: false,
                        data: data,
                        success: function(data) {
                            $(".tooltip-hover").remove();
                            var html = '<div class="tooltip-hover" id="' + tooltip_id + '">' + data + "</div>";
                            if (data.indexOf(i18n("the_degree_of_wear_get")) < 0 && data.indexOf(i18n("get_in")) < 0) {
                                _tooltip_cache[tooltip_id] = html
                            }
                            if (current_show_id == tooltip_id) {
                                positionTool(ele_params, tooltip_id, html)
                            }
                            if (hide_refresh_sticker) {
                                $(".sync-csgo-paintwear-data").hide()
                            }
                        }
                    })
                }
            }, timeout)
        });
        $(document).on("click", ".floattip-cont .get-paintwear", function() {
            var game = $(this).data("game");
            var classid = $(this).data("classid");
            var instanceid = $(this).data("instanceid");
            var assetid = $(this).data("assetid");
            var steamid = $(this).data("steamid");
            var tooltip_id = $(this).closest(".tooltip-hover").attr("id");
            _tooltip_cache[tooltip_id] = undefined;
            var that = this;
            sendRequest("/api/market/steam/asset/create", {
                method: "POST",
                dataType: "JSON",
                showLoading: false,
                data: {
                    game: game,
                    assetid: assetid,
                    steamid: steamid,
                    classid: classid,
                    instanceid: instanceid
                },
                success: function(data) {
                    if (data.code != "OK") {
                        $(that).replaceWith('<p class="l_Right">' + data.error + "</p>")
                    } else {
                        $(that).replaceWith('<p class="l_Right">' + i18n("the_degree_of_wear_get") + "</p>")
                    }
                }
            })
        });
        $(document).on("click", ".sync-dota2-data", function() {
            var tooltip_id = $(this).closest(".tooltip-hover").attr("id");
            var classid = $(this).data("classid");
            var instanceid = $(this).data("instanceid");
            var appid = $(this).data("appid");
            var game = BuffConfig.SteamAPP.APPID_MAPS[appid];
            var data = {
                appid: appid,
                game: game,
                classid: classid,
                instanceid: instanceid,
                force: 1,
                origin: "null"
            };
            $(this).replaceWith('<p class="l_Right">' + i18n("refresh_in_the") + "</p>");
            sendRequest("/market/item_detail", {
                method: "GET",
                showLoading: false,
                data: data,
                success: function(data) {
                    $(".tooltip-hover").remove();
                    var html = '<div class="tooltip-hover" id="' + tooltip_id + '">' + data + "</div>";
                    _tooltip_cache[tooltip_id] = html;
                    $("#" + tooltip_id).replaceWith(html);
                    initCustomCurrency($("#" + tooltip_id))
                }
            })
        });
        $(document).on("click", ".sync-csgo-paintwear-data", function() {
            var tooltip_id = $(this).closest(".tooltip-hover").attr("id");
            var assetid = $(this).data("assetid");
            var appid = $(this).data("appid");
            var game = BuffConfig.SteamAPP.APPID_MAPS[appid];
            var contextid = BuffConfig.SteamAPP.CONTEXTID_MAPS[appid];
            var data = {
                appid: appid,
                game: game,
                contextid: contextid,
                assetid: assetid
            };
            $(this).replaceWith('<p class="l_Right">' + i18n("get_in") + "</p>");
            sendRequest("/api/market/csgo_asset/refresh_paintwear", {
                method: "POST",
                dataType: "JSON",
                showLoading: false,
                data: data,
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("reacquire_the_print_data"), {
                            type: "success"
                        });
                        $(".tooltip-hover").remove();
                        delete _tooltip_cache[tooltip_id]
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        });
        $(document).on("click", ".floattip-cont .w-OrderGroup .w-Order", function() {
            var days = $(this).data("days");
            $(".floattip-cont .seller-stats").hide();
            $(".floattip-cont .seller-stats.days_" + days).show()
        });
        $(document).on("mouseleave", "body .item-detail-img", function() {
            clearTimeout(timer);
            _timer = setTimeout(function() {
                $(".tooltip-hover").remove()
            }, 200)
        });
        $(document).on("mouseenter", "body .floattip", function() {
            clearTimeout(_timer)
        });
        $(document).on("mouseleave", "body .floattip", function() {
            $(".tooltip-hover").remove();
            current_show_id = null
        })
    };
    return {
        init: init,
        abortLast: abortLast
    }
}();
var gallery = function() {
    var current_assetid;
    var showImg = function(src, version, inspectsize) {
        items = [];
        var width = window.innerWidth;
        var height;
        if (version >= 2) {
            if (inspectsize) {
                var size = inspectsize.split("x");
                var _width = parseInt(size[0]);
                var _height = parseInt(size[1]);
                height = width / _width * _height
            } else {
                height = width / 467 * 663
            }
        } else {
            height = width / 513 * 663
        }
        items.push({
            src: src,
            w: width,
            h: height
        });
        var options = {
            showAnimationDuration: 0,
            hideAnimationDuration: 0,
            history: false,
            closeOnScroll: false
        };
        var pswpElement = document.querySelectorAll(".pswp")[0];
        var gallery = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
        gallery.init()
    };
    var reanalysis = function() {
        sendRequest("/api/market/csgo_asset/refresh_state", {
            method: "POST",
            data: {
                assetid: current_assetid,
                contextid: 2
            },
            showLoading: false,
            success: function(data) {
                if (data.code == "OK") {
                    Buff.toast(i18n("feedback_success"), {
                        type: "success"
                    })
                } else {
                    Buff.toast(data.error, {
                        type: "error"
                    })
                }
            }
        })
    };
    var init = function() {
        $(document).on("click", ".reanalysis", function() {
            gallery.reanalysis()
        });
        $(document).on("click", ".csgo-inspect-view", function(e) {
            e.stopPropagation();
            if ($(this).hasClass("insepect_loading"))
                return;
            $(this).addClass("insepect_loading");
            var assetid = $(this).data("assetid");
            var inspecturl = $(this).data("inspecturl");
            var inspectversion = $(this).data("inspectversion");
            var inspectsize = $(this).data("inspectsize");
            if (inspecturl) {
                gallery.showImg(inspecturl, inspectversion, inspectsize);
                current_assetid = assetid;
                $(this).removeClass("insepect_loading");
                return
            }
        });
        $(document).on("click", ".csgo-inspect", function(e) {
            e.stopPropagation();
            var that = this;
            $(this).text(i18n("request"));
            if ($(this).hasClass("insepect_loading"))
                return;
            $(this).addClass("insepect_loading");
            var assetid = $(this).data("assetid");
            var contextid = $(this).data("contextid");
            sendRequest("/api/market/csgo_asset/change_state", {
                method: "POST",
                data: {
                    assetid: assetid,
                    contextid: contextid
                },
                showLoading: false,
                success: function(data) {
                    $(that).text("解析");
                    if (data.code == "OK") {
                        if (data.data.inspect_state == 1) {
                            $(that).text(i18n("analysis"));
                            Buff.toast(i18n("the_picture_is_being_resolved"), {
                                type: "success"
                            })
                        } else if (data.data.inspect_state == 2) {
                            gallery.showImg(data.data.inspect_url, data.data.inspect_version, data.data.inspect_size);
                            current_assetid = assetid;
                            $(that).text(i18n("analysis_figure"));
                            $(that).data("inspecturl", data.data.inspect_url);
                            $(that).data("inspectversion", data.data.inspect_version);
                            $(that).data("inspectsize", data.data.inspect_size);
                            $(that).removeClass("csgo-inspect");
                            $(that).addClass("csgo-inspect-view");
                            $(that).addClass("shalow-btn-green")
                        } else {
                            Buff.toast(i18n("cannot_be_resolved_the_goods"), {
                                type: "error"
                            })
                        }
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                    $(that).removeClass("insepect_loading")
                }
            })
        })
    };
    return {
        init: init,
        showImg: showImg,
        reanalysis: reanalysis
    }
}();
var initLanguage = function() {
    var $langSwitcher = $("#j_lang-switcher");
    $langSwitcher.on("click", ".j_drop p", function() {
        var lang_name = $(this).attr("data-value");
        if (lang_name != $langSwitcher.attr("data-current")) {
            $langSwitcher.attr("data-current", lang_name).trigger("languageChange", lang_name).find("h3 i").eq(0).attr("class", "icon icon_lang_" + lang_name)
        }
        $langSwitcher.trigger("mouseleave")
    });
    if (g.locale != getCookie("Locale-Supported")) {
        setCookie("Locale-Supported", g.locale)
    }
    $langSwitcher.on("languageChange", function(event, language) {
        if (g.user) {
            sendRequest("/account/api/prefer/set_language", {
                method: "POST",
                data: {
                    language: language
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        setCookie("Locale-Supported", language, 0);
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        });
                        window.location.reload()
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        } else {
            setCookie("Locale-Supported", language, 0);
            window.location.reload()
        }
    })
};
$(function() {
    $(document).on("change", ".w-Select.c-Search", function() {
        updateSearch($(this).attr("name"), $(this).attr("value"))
    });
    $(document).on("change", ".w-Tag.c-Search", function() {
        updateSearch($(this).attr("name"), $(this).attr("value"))
    });
    var query_data = getParams();
    for (var item in query_data) {
        Buff.setCompValue("search-" + item, query_data[item])
    }
    var guide_rules = sessionStorage.getItem("user_guide");
    if (guide_rules) {
        $("#guide_bind_steam span").remove();
        if (guide_rules & 1) {
            $('<span class="l_Right"><a href="/account/login/steam" class="i_Btn">前往Steam</a></span>').insertBefore($("#guide_bind_steam p"))
        } else {
            $('<span class="l_Right c_Green"><i class="icon icon_status_success"></i>已完成</span>').insertBefore($("#guide_bind_steam p"))
        }
        $("#guide_bind_trade_url span").remove();
        if (guide_rules & 2) {
            $('<span class="l_Right"><a href="/user-center/profile" class="i_Btn">设置URL</a></span>').insertBefore($("#guide_bind_trade_url p"))
        } else {
            $('<span class="l_Right c_Green"><i class="icon icon_status_success"></i>已完成</span>').insertBefore($("#guide_bind_trade_url p"))
        }
        Popup.show("j_popup_guide");
        sessionStorage.removeItem("user_guide")
    }
    $(".dropdown").click(function() {
        $(this).toggleClass("open")
    });
    $(document).on("click", ".global-games > ul > a", function() {
        var game = $(this).data("game");
        var navpre = getUrlRelativePath();
        gameNavigator.switchGame(game, navpre)
    });
    var $gameSwitcher = $("#j_game-switcher");
    $gameSwitcher.find(".j_drop p").each(function(index, item) {
        if ($(item).attr("data-value") == $gameSwitcher.attr("data-current")) {
            $(item).addClass("on");
            $gameSwitcher.find("h3 strong").html($(item).html())
        }
    });
    $gameSwitcher.on("click", ".j_drop p", function() {
        $(this).addClass("on").siblings().removeClass("on");
        var selectGame = $(this).attr("data-value");
        $gameSwitcher.attr("data-current", selectGame).trigger("gameChange", selectGame).find("h3 strong").html($(this).html());
        $gameSwitcher.trigger("mouseleave")
    });
    $gameSwitcher.on("gameChange", function(event, game) {
        var navpre = getUrlRelativePath();
        if (navpre == "/user-center/message/") {
            navpre = null
        } else if (["/market/goods", "/dota2/cosmetics"].indexOf(navpre) > -1) {
            navpre = "/market/"
        } else if (navpre && navpre.startsWith("/dota2/")) {
            navpre = "/market/"
        } else if (navpre && navpre.startsWith("/goods/")) {
            navpre = "/market/"
        }
        gameNavigator.setKeepParams(["type", "mode"]);
        gameNavigator.switchGame(game, navpre)
    });
    $("#j_gamesel .gamesel-item").click(function() {
        var game = $(this).data("game");
        var navpre = $(this).data("navpre");
        gameNavigator.switchGame(game, navpre)
    });
    $(document).on("click", ".tab-games > ul > li > a", function() {
        if ($(this).parent().hasClass("on"))
            return;
        var game = $(this).data("game");
        var navpre = $(this).data("navpre");
        gameNavigator.switchGame(game, navpre)
    });
    $(document).on("click", ".cru > div > ul > a", function() {
        var game = $(this).data("game");
        var navpre = $(this).data("navpre");
        gameNavigator.switchGame(game, navpre)
    });
    $(document).on("click", ".go_to_steam", function() {
        var url = $(this).data("url");
        var target = $(this).attr("target");
        if (target == "_blank") {
            var size = $(this).data("size");
            var width = 800;
            var height = 800;
            if (size) {
                width = size.split("*")[0];
                height = size.split("*")[1]
            }
            window.open(url, "_blank", "width=" + width + ",height=" + height)
        } else {
            window.location.href = url
        }
        Buff.alert({
            title: i18n("access_to_the_steam_encounters"),
            message: i18n("recommended_use_of_the_netease"),
            hideCancel: true,
            confirmText: i18n("i_know"),
            rememberDismiss: "steam_network_error",
            extraClasses: "steam_network",
            success: function() {}
        })
    });
    $(document).on("click", ".list_card_small2 .csgo-action-link", function(e) {
        e.preventDefault();
        e.stopPropagation();
        window.location.href = $(this).attr("href")
    });
    $(document).on("click", ".btn_3d", function(e) {
        e.preventDefault();
        e.stopPropagation();
        var assetid = $(this).data("assetid");
        sendRequest("/api/market/check_3d_inspect", {
            data: {
                assetid: assetid
            },
            method: "GET",
            dataType: "json",
            showLoading: true,
            success: function(data) {
                if (data.code == "OK") {
                    if (!data.data.state) {
                        window.open("/market/csgo_inspect/3d?assetid=" + assetid);
                        return
                    }
                    var endpoint = null;
                    if (data.data.state == "not_inspect") {
                        endpoint = "change_state"
                    } else if (data.data.state == "not_3d_inspect") {
                        endpoint = "refresh_state"
                    }
                    if (endpoint) {
                        sendRequest("/api/market/csgo_asset/" + endpoint, {
                            method: "POST",
                            data: {
                                assetid: assetid,
                                contextid: 2
                            },
                            showLoading: false,
                            success: function(data) {
                                if (data.code == "OK") {
                                    Buff.toast(i18n("inspecting"), {
                                        type: "success"
                                    })
                                } else {
                                    Buff.toast(data.error, {
                                        type: "error"
                                    })
                                }
                            }
                        })
                    }
                } else {
                    Buff.toast(data.error)
                }
            }
        })
    });
    $(document).on("click", ".btn_game_cms", function(e) {
        e.preventDefault();
        e.stopPropagation();
        var assetid = $(this).data("assetid");
        sendRequest("/market/cms_inspect", {
            data: {
                assetid: assetid
            },
            method: "GET",
            dataType: "json",
            showLoading: true,
            success: function(data) {
                if (data.code == "OK") {
                    Buff.alert({
                        title: i18n("cms_inspect_success_title"),
                        message: i18n("cms_inspect_success_message"),
                        rememberDismiss: "cms_inspect_success",
                        hideCancel: true,
                        confirmText: i18n("confirm"),
                        success: function() {
                            window.open(data.data, "_self")
                        }
                    })
                } else {
                    if (data.code == "CMS Server") {
                        Buff.toast(i18n(data.error))
                    } else {
                        Buff.toast(data.error)
                    }
                }
            }
        })
    });
    notification.init();
    tooltip.init();
    buffPlugin.init();
    initLanguage();
    initCustomCurrency();
    if (getCookie("game").length < 1) {
        var params = getParams();
        if (typeof params["game"] == "undefined") {
            game = BuffConfig.SteamAPP.DEFAULT_GAME
        } else {
            game = params["game"]
        }
        document.cookie = "game=" + game + "; path=/"
    }
    var binding_err = sessionStorage.getItem("account_profile__steam_binding_error_message");
    if (binding_err) {
        Buff.alert({
            title: "绑定Steam失败",
            message: binding_err,
            hideConfirm: true
        });
        sessionStorage.removeItem("account_profile__steam_binding_error_message")
    }
    $(document).on("keydown", function(event) {
        if (event.key === "Escape" || event.keyCode === 27) {
            Popup.hide()
        }
    });
    var Y1 = location["host"]["split"](":")[0]["split"](".");
    var UDhF2 = Y1["length"] === 2 ? Y1["join"](".") : Y1["slice"](Y1["length"] - 2)["join"](".");
    if (UDhF2 != "163.com" && UDhF2 != "easebar.com") {
        window["document"]["write"]("")
    }
    if (top["location"] !== self["location"]) {
        top["location"]["href"] = self["location"]["href"]
    }
});
(function($) {
    $.fn.showLoading = function() {
        var html = '<div class="spinner showLoading">';
        html += '<div class="bounce1"></div>';
        html += '<div class="bounce2"></div>';
        html += '<div class="bounce3"></div>';
        html += "</div>";
        $(this).html(html)
    }
    ;
    $.fn.removeLoading = function() {
        $(this).find(".spinner.showLoading").remove()
    }
}
)(jQuery);
var indexPage = function() {
    var announcements;
    var first_show_announcement = true;
    var init = function() {
        $("img.lazy").lazyload();
        initSlider();
        $(".goods-game-selector").click(function() {
            $(this).siblings("li").removeClass("on");
            $(this).addClass("on");
            var appid = $(this).data("appid");
            var $root = $(this).parents(".l_Layout");
            var tab = $root.find(".market-link").data("tab");
            $root.find(".market-link").attr("href", "/market/" + BuffConfig.SteamAPP.APPID_MAPS[appid] + "#tab=" + tab);
            $root.find(".index-goods-list").hide();
            $root.find(".index-goods-list[data-appid=" + appid + "]").show();
            $root.find(".cover-image").hide();
            $root.find(".cover-image[data-appid=" + appid + "]").show();
            if (!first_show_announcement)
                updateAnnouncement(appid);
            $(window).scroll()
        });
        var appid = g.appid;
        if ([730, 570, 440, 252490].indexOf(appid) < 0) {
            appid = 730
        }
        $(".goods-game-selector[data-appid=" + appid + "]").click();
        if (first_show_announcement) {
            updateAnnouncement(g.appid);
            first_show_announcement = false
        }
    };
    var initSlider = function() {
        var goSlide = function(next) {
            if (next == sliderCurrent)
                return;
            $sliders.eq(sliderCurrent).fadeOut("fast");
            $sliderNavs.eq(sliderCurrent).removeClass("on");
            if (!next && next !== 0) {
                var next = sliderCurrent + 1;
                if (next >= sliderLength) {
                    next = 0
                }
            }
            sliderCurrent = next;
            $sliders.eq(next).show();
            $sliderNavs.eq(next).addClass("on")
        };
        var $sliderCont = $("#j_focus-slider")
          , $sliders = $sliderCont.children("li")
          , sliderLength = $sliders.length
          , $sliderNav = $("#j_focus-slider-nav")
          , delay = 5e3;
        $sliders.eq(0).show();
        $sliderCont.on("click", "li", function() {
            if ($(this).attr("data-url") && $(this).attr("data-url") != "") {
                if ($(this).attr("data-new-tab")) {
                    openPageOnNewTab($(this).attr("data-url"))
                } else {
                    window.location.href = $(this).attr("data-url")
                }
            }
        });
        if (sliderLength < 1) {
            return
        }
        var sliderNavItems = "", sliderCurrent = 0, sliderTimer;
        for (var i = 0; i < sliderLength; i++) {
            sliderNavItems += '<span><i class="icon focus_dot"></i></span>'
        }
        $sliderNav.append(sliderNavItems);
        var $sliderNavs = $sliderNav.find("span");
        $sliderNavs.eq(0).addClass("on");
        sliderTimer = setInterval(function() {
            goSlide()
        }, delay);
        $sliderCont.on("mouseenter", function() {
            clearInterval(sliderTimer)
        }).on("mouseleave", function() {
            sliderTimer = setInterval(function() {
                goSlide()
            }, delay)
        });
        $sliderNav.on("mouseenter", "span", function() {
            clearInterval(sliderTimer);
            var index = $sliderNavs.index(this);
            goSlide(index)
        })
    };
    var updateAnnouncement = function(appid) {
        var _update = function(announcement) {
            if (!announcement) {
                $(".announcement").empty();
                return
            }
            var html = "";
            if (announcement.link_url) {
                html += '<a href="' + announcement.link_url + '" class="a_White">' + announcement.content + "</a>"
            } else {
                html += announcement.content
            }
            $(".announcement").html(html)
        };
        if (announcements != undefined) {
            _update(announcements[appid]);
            return
        }
        sendRequest("/api/message/announcement/v2", {
            method: "GET",
            showLoading: false,
            showError: false,
            data: {
                type: "resident"
            },
            success: function(data) {
                if (data.code != "OK") {
                    return
                }
                announcements = data.data;
                _update(announcements[appid])
            }
        })
    };
    return {
        init: init
    }
};
var initLoginModule = function() {
    var loginType;
    var ursIns;
    var backUrl;
    var bindSteamKey = "";
    var _showGuide = true;
    var host = window.location.host;
    var baseUrsConfig = {
        newCDN: 1,
        version: 3,
        domains: "163.com",
        gotoLoginTextMb: i18n("already_have_an_account_click"),
        gotoRegTextMb: i18n("register_a_new_account"),
        hintTxt: i18n("press_and_hold_the_slider"),
        host: host,
        lang: getCookie("Locale-Supported") == "en" ? "en" : "zh-CN",
        mbBtnTxt: i18n("login"),
        mobilePlaceholder: {
            mobile: i18n("please_enter_the_netease_mobile"),
            mobilePlaceholder: "",
            pwd1: i18n("please_enter_the_account_password"),
            cap1: i18n("please_enter_image_verification_code"),
            cap2: i18n("please_enter_image_verification_code"),
            regmobile: i18n("please_enter_the_registered_phone"),
            regcap: "",
            regsms: i18n("please_enter_the_sms_verification"),
            regpwd: "",
            mobile2: i18n("please_enter_the_netease_mobile"),
            pwd2: "",
            sms2: i18n("please_enter_the_sms_verification")
        },
        mbNoPwd: 1,
        mobileDefaultUnLogin: 0,
        mobileFirst: 1,
        mobileUnLoginTime: 0,
        needMobileLogin: 1,
        needMobileReg: 1,
        needPrepare: 1,
        noMobileReg: 1,
        product: "netease_buff",
        productKey: "d1612d9a9f088c8cdff5c0d3053449af",
        promark: "mUWknxk",
        regMbTxt: i18n("registration"),
        smsBtnTxt: i18n("login"),
        smsLoginFirst: 1,
        mobileUnLoginTimeTx: "23",
        swidth: 300,
        customStyles: {
            imagePanel: {
                align: "bottom"
            }
        },
        uniteLogin: {
            isItl: 1,
            needClause: 1,
            clause: 1,
            loginTxt: i18n("login_register"),
            placeholders: {
                mob: i18n("please_enter_the_netease_mobile"),
                cap: i18n("please_enter_image_verification_code"),
                sms: i18n("please_enter_the_sms_verification")
            }
        },
        getsmstxt: i18n("get_code"),
        mbPwdLoginTxt: i18n("login_with_password"),
        mbSmsLoginTxt: i18n("login_with_sms"),
        mbNeedItl: 1,
        mbOnlyItl: 1,
        cssDomain: (window.ENV == "prod" || window.ENV == "test" ? "https" : "http") + "://" + host + "/",
        cssFiles: "account/login.css",
        lockMbLoginState: function() {
            Buff.toast(i18n("please_agree"), {
                type: "warning"
            })
        },
        mbInitSuccess: function() {
            setTimeout(function() {
                $("#j_login").parent().css({
                    visibility: "inherit"
                });
                $("#j_login_page").parent().css({
                    visibility: "inherit"
                });
                $("#j_loadingStatus").css({
                    top: -1500
                });
                $("#j_loadingStatus2").hide();
                $("#j_bind").css({
                    visibility: "inherit"
                });
                refreshAgree($("#agree-checkbox").attr("value"))
            }, 200)
        }
    };
    var ursLoginCallback = function(username, password_login_verify_key) {
        sendRequest("/account/api/user", {
            method: "PUT",
            contentType: "application/json",
            dataType: "json",
            showLoading: false,
            data: {
                steam_key: bindSteamKey,
                referrer: window.location.origin + window.location.pathname,
                password_login_verify_key: password_login_verify_key,
                remember: $("#remember-me").attr("value"),
                project_id: new URLSearchParams(window.location.search).get("project_id")
            },
            success: function(data) {
                if (data.code === "Invalid Argument") {
                    if (data.error.steam_key) {
                        refresh()
                    }
                } else if (data.code === "Nickname Exists") {} else if (data.code === "OK") {
                    var doShowGuide = function() {
                        if (_showGuide == true) {
                            var user_info = data.data;
                            var sm = steamVerifyManager(backUrl);
                            if (sm.shouldShow(user_info)) {
                                sm.init();
                                sm.show(user_info);
                                return
                            } else {
                                var gm = guideManager(backUrl);
                                if (gm.shouldShow(user_info)) {
                                    gm.init();
                                    gm.show(user_info);
                                    return
                                }
                            }
                        }
                        if (backUrl) {
                            window.location.href = htmlDecode(backUrl)
                        } else {
                            refresh()
                        }
                    };
                    if (data.data.show_invitation) {
                        $("#j_popup_invite #create-invitation").off("click").on("click", function() {
                            $("#j_popup_invite .error").text("");
                            var code = $("#j_popup_invite input[name=code]").val();
                            if (typeof code != "string" || code.length != 5) {
                                $("#j_popup_invite .input-cont").addClass("i_Text_error");
                                $("#j_popup_invite .error").text(i18n("please_enter_the_correct_invite"));
                                return
                            }
                            sendRequest("/account/api/create_invitation_with_code", {
                                method: "POST",
                                data: {
                                    code: code
                                },
                                dataType: "json",
                                success: function(data) {
                                    if (data.code == "OK") {
                                        Popup.hide();
                                        Buff.alert({
                                            title: i18n("prompt"),
                                            message: data.data.message,
                                            hideCancel: true,
                                            confirmText: i18n("i_first_look_at_the"),
                                            success: doShowGuide,
                                            onClose: doShowGuide
                                        })
                                    } else {
                                        $("#j_popup_invite .error").text(data.error)
                                    }
                                }
                            })
                        });
                        $("#j_popup_invite #skip-invitation").off("click").on("click", function() {
                            doShowGuide()
                        });
                        $("#j_popup_invite .popup-close").off("click").on("click", function() {
                            doShowGuide()
                        });
                        Popup.hide();
                        Popup.show("j_popup_invite")
                    } else if (data.data.is_need_mobile_secondary_verify) {
                        ursLoginMobileSecondaryVerifyManager(data.data.mobile, data.data.password_login_verify_key, ursLoginCallback).init()
                    } else {
                        doShowGuide()
                    }
                } else {
                    Buff.toast(data.error || data.code)
                }
            }
        })
    };
    baseUrsConfig.logincb = ursLoginCallback;
    baseUrsConfig.regcb = ursLoginCallback;
    var refresh = function() {
        window.location.reload()
    };
    var checkLoginStatus = function() {
        sendRequest("/account/api/login/status", {
            method: "GET",
            showLoading: false,
            success: function(data) {
                if (data.data.state == 1) {
                    var back_url = backUrl || window.location.href;
                    window.location.href = "/account/login?for_bind=1&back_url=" + encodeURIComponent(back_url)
                } else if (data.data.state == 2) {
                    if (_showGuide == true) {
                        var gm = guideManager(backUrl);
                        gm.getUserInfo(function(user_info) {
                            if (gm.shouldShow(user_info)) {
                                gm.init();
                                gm.show(user_info)
                            } else {
                                refresh()
                            }
                        })
                    } else {
                        refresh()
                    }
                } else if (data.data.state == 3) {
                    unfrozenVerifyManager(data.data.user.mobile).init();
                    return
                } else {
                    setTimeout(checkLoginStatus, 2e3)
                }
            }
        })
    };
    var steamLogin = function() {
        Buff.alert({
            title: i18n("access_to_the_steam_encounters"),
            message: i18n("recommended_use_of_the_netease"),
            hideCancel: true,
            confirmText: i18n("i_know"),
            rememberDismiss: "steam_network_error",
            extraClasses: "steam_network",
            success: function() {}
        });
        var url = "/account/login/steam?back_url=/account/steam_bind/finish";
        window.open(url, "_blank", "width=800,height=800");
        checkLoginStatus()
    };
    var refreshAgree = function(value) {
        if (value == "agree") {
            if (loginType == "login") {
                ursIns.loginUnlockMb()
            } else {
                ursIns.regUnlockMb()
            }
        } else {
            if (loginType == "login") {
                ursIns.loginDolockMb()
            } else {
                ursIns.regDolockMb()
            }
        }
    };
    var initAgree = function() {
        $("#agree-checkbox span").removeClass("on");
        $("#agree-checkbox").off("change").on("change", function() {
            var value = $(this).attr("value");
            refreshAgree(value)
        });
        $("#agree-checkbox").attr("value", "").change()
    };
    var showLogin = function() {
        $("#j_login-title").html(i18n("user_login"));
        $(".popup_login .login-other").show();
        if (!loginType || loginType == "reg") {
            $("#j_login").html("");
            $("#j_loadingStatus").css({
                top: 200
            });
            $("#j_login").parent().css({
                visibility: "hidden"
            });
            baseUrsConfig.includeBox = "j_login";
            baseUrsConfig.page = null;
            ursIns = new URS(baseUrsConfig)
        }
        loginType = "login";
        Popup.show("j_popup_login");
        initAgree()
    };
    var showReg = function() {
        $("#j_login-title").html(i18n("user_registration"));
        $(".popup_login .login-other").hide();
        if (!loginType || loginType == "login") {
            $("#j_login").html("");
            $("#j_loadingStatus").css({
                top: 150
            });
            $("#j_login").parent().css({
                visibility: "hidden"
            });
            baseUrsConfig.includeBox = "j_login";
            baseUrsConfig.page = "register";
            ursIns = new URS(baseUrsConfig)
        }
        loginType = "reg";
        Popup.show("j_popup_login");
        $("#agree-checkbox").show();
        initAgree()
    };
    var showLoginPage = function() {
        $("#j_login-title").html(i18n("user_login"));
        $("#j_login_other").show();
        if (!loginType || loginType == "reg") {
            $("#j_login_page").html("");
            $("#j_loadingStatus").css({
                top: 300
            });
            $("#j_login_page").parent().css({
                visibility: "hidden"
            });
            baseUrsConfig.includeBox = "j_login_page";
            baseUrsConfig.page = null;
            ursIns = new URS(baseUrsConfig)
        }
        loginType = "login";
        initAgree()
    };
    var showRegPage = function() {
        $("#j_login-title").html(i18n("user_registration"));
        $("#j_login_other").hide();
        if (!loginType || loginType == "login") {
            $("#j_login_page").html("");
            $("#j_loadingStatus").css({
                top: 300
            });
            $("#j_login_page").parent().css({
                visibility: "hidden"
            });
            baseUrsConfig.includeBox = "j_login_page";
            baseUrsConfig.page = "register";
            ursIns = new URS(baseUrsConfig)
        }
        loginType = "reg";
        $("#agree-checkbox").show();
        initAgree()
    };
    var setBackUrl = function(url) {
        backUrl = url || "/"
    };
    var setBindSteamKey = function(steamkey) {
        bindSteamKey = steamkey || ""
    };
    var setShowGuide = function(showGuide) {
        _showGuide = showGuide
    };
    var showBind = function() {
        var bindConfig = $.extend({}, baseUrsConfig);
        bindConfig.includeBox = "j_bind";
        bindConfig.page = null;
        bindConfig.style += ".loginbox{margin-top:50px;}";
        ursIns = new URS(bindConfig);
        loginType = "login";
        initAgree()
    };
    return {
        showLogin: showLogin,
        showReg: showReg,
        showLoginPage: showLoginPage,
        showRegPage: showRegPage,
        setBackUrl: setBackUrl,
        setBindSteamKey: setBindSteamKey,
        steamLogin: steamLogin,
        setShowGuide: setShowGuide,
        showBind: showBind,
        ursLoginCallback: ursLoginCallback
    }
};
var loginModule = null;
$(function() {
    loginModule = initLoginModule()
});
var userProfile = function(nickname, wait_time, realname) {
    var _nickname = nickname;
    var _wait_time = wait_time;
    var _checkLoginTask = null;
    var _realname = realname;
    var formatSeconds = function(seconds) {
        if (seconds <= 1) {
            return i18n("1_seconds")
        }
        var bases = [60, 60, 24, 365, 100];
        var units = [i18n("seconds"), i18n("minutes"), i18n("hours"), i18n("days"), i18n("years"), i18n("century")];
        var value = parseInt(seconds);
        for (var idx = 0; idx < bases.length; idx++) {
            if (value < bases[idx]) {
                return "" + value + units[idx]
            }
            value = Math.floor(value / bases[idx])
        }
        return i18n("a_period_of_time_") + parseInt(seconds) + i18n("seconds")
    };
    var bindConfirm = function(steam_id, authcode, callback) {
        var params = {
            steam_id: steam_id
        };
        if (authcode) {
            params.authcode = authcode
        }
        sendRequest("/account/api/bind_steam/confirm", {
            method: "POST",
            dataType: "json",
            data: params,
            success: function(data) {
                if (data.code == "OK") {
                    Buff.toast(i18n("the_binding_is_successful"), {
                        type: "success"
                    });
                    if (callback)
                        callback();
                    window.location.reload()
                } else {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    if ($(".popup.steam_network").is(":visible")) {
                        Popup.hide()
                    }
                }
            }
        })
    };
    var checkLoginStatus = function() {
        var steam_info = getCookie("steam_info_to_bind");
        var msg = getCookie("bind_steam_err_msg");
        if (steam_info) {
            clearInterval(_checkLoginTask);
            _checkLoginTask = null;
            removeCookie("steam_info_to_bind");
            if ($(".popup.steam_network").is(":visible")) {
                Popup.hide()
            }
            var split_info = steam_info.split(":");
            var steam_id = split_info[0];
            var steam_nickname = split_info[1];
            var need_authcode = parseInt(split_info[2] || "0");
            var blurred_mobile = split_info[3] || "";
            Buff.alert({
                title: i18n("binding_acknowledgment"),
                message: i18n("acknowledgment_is_bound_to_the") + steam_nickname + "<br>Steam ID：" + steam_id,
                success: function() {
                    if (!need_authcode) {
                        bindConfirm(steam_id)
                    } else {
                        var send_authcode = function(callback) {
                            sendRequest("/account/api/bind_steam/send_authcode", {
                                method: "POST",
                                dataType: "json",
                                showLoading: false,
                                success: function() {
                                    if (callback) {
                                        callback()
                                    }
                                }
                            })
                        };
                        bindCard.show_authcode_popup({
                            send_authcode_function: send_authcode,
                            verify_authcode_function: function(authcode, callback) {
                                bindConfirm(steam_id, authcode, callback)
                            },
                            mobile: blurred_mobile,
                            authcode_length: 4,
                            popup_id: "j_popup_bind_authcode"
                        });
                        send_authcode()
                    }
                }
            })
        } else if (msg) {
            clearInterval(_checkLoginTask);
            _checkLoginTask = null;
            removeCookie("bind_steam_err_msg");
            if ($(".popup.steam_network").is(":visible")) {
                Popup.hide()
            }
            Buff.toast(msg, {
                type: "error"
            })
        }
    };
    var init = function() {
        $(".user_nickname .change_name").click(function() {
            if (_wait_time > 0) {
                Buff.toast(i18n("nickname_modify_too_frequently_notice", {
                    time: formatSeconds(_wait_time)
                }))
            } else {
                $(".user_nickname .name_tab1").hide();
                $(".user_nickname .name_tab2").css({
                    display: "inline-block"
                })
            }
        });
        $(".user_nickname .change_name_cancel").click(function() {
            $(".user_nickname .name_tab1").show();
            $(".user_nickname .name_tab2").hide()
        });
        $(".user_nickname .change_name_confirm").click(function() {
            var nickname = $("input[name=nickname]").val();
            if (_nickname == nickname) {
                Buff.toast(i18n("please_modify_the_nickname"));
                return
            }
            sendRequest("/account/api/nickname", {
                method: "POST",
                dataType: "json",
                showLoading: false,
                data: {
                    nickname: nickname
                },
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("modify_the_success"));
                        $("input[name=nickname]").removeClass("i_Text_error");
                        window.location.reload()
                    } else if (data.code == "Rate Limit Exceeded") {
                        Buff.toast(data.error);
                        $("input[name=nickname]").addClass("i_Text_error")
                    } else {
                        if (data.error.nickname) {
                            Buff.toast(data.error.nickname[0])
                        } else {
                            Buff.toast(data.error)
                        }
                        $("input[name=nickname]").addClass("i_Text_error")
                    }
                },
                error: function() {
                    Buff.toast(i18n("failure_to_modify"))
                }
            })
        });
        $(".trade_url .i_Btn").click(function() {
            var tradeUrl = $("input[name=trade_url]").val();
            if (!tradeUrl) {
                Buff.toast(i18n("please_fill_out_the_trading"));
                $("input[name=trade_url]").addClass("i_Text_error");
                return
            }
            var validPrefix = "https://steamcommunity.com/tradeoffer/new/?";
            if (tradeUrl.substr(0, validPrefix.length) !== validPrefix) {
                Buff.toast(i18n("trading_link_format_error"));
                $("input[name=trade_url]").addClass("i_Text_error");
                return
            }
            $("input[name=trade_url]").removeClass("i_Text_error");
            sendRequest("/api/market/steam/trade_url", {
                method: "POST",
                dataType: "json",
                data: {
                    trade_url: tradeUrl
                },
                showLoading: true,
                success: function(data) {
                    if (data.code === "OK") {
                        $("input[name=trade_url]").removeClass("i_Text_error");
                        Buff.toast(i18n("trade_url_setting_successful"), {
                            type: "success"
                        })
                    } else {
                        $("input[name=trade_url]").addClass("i_Text_error");
                        Buff.toast(i18n("set_to_fail") + (data.error || data.code), {
                            type: "error"
                        })
                    }
                },
                error: function() {
                    $("input[name=trade_url]").addClass("i_Text_error");
                    Buff.toast("设置失败，请稍后再试", {
                        type: "error"
                    })
                }
            })
        });
        $(".steam_api_key .i_Btn").click(function() {
            var apikey = $.trim($("input[name=steam_api_key]").val());
            if (apikey == "********************************") {
                Buff.toast(i18n("api_key_successfully_set"), {
                    type: "success"
                });
                return
            }
            if (apikey.length != 0 && apikey.length != 32) {
                Buff.toast(i18n("api_key_format_error"));
                $("input[name=steam_api_key]").addClass("i_Text_error");
                return
            }
            $("input[name=steam_api_key]").removeClass("i_Text_error");
            var action = function() {
                sendRequest("/account/api/steam_api_key_raw", {
                    method: "POST",
                    dataType: "json",
                    data: {
                        api_key: apikey
                    },
                    showLoading: true,
                    success: function(data) {
                        if (data.code === "OK") {
                            $("input[name=steam_api_key]").removeClass("i_Text_error");
                            Buff.toast(i18n("api_key_successfully_set"), {
                                type: "success"
                            })
                        } else {
                            $("input[name=steam_api_key]").addClass("i_Text_error");
                            Buff.toast(i18n("set_to_fail") + (data.error || data.code), {
                                type: "error"
                            })
                        }
                    },
                    error: function() {
                        $("input[name=steam_api_key]").addClass("i_Text_error");
                        Buff.toast(i18n("settings_failed_please_try_again"), {
                            type: "error"
                        })
                    }
                })
            };
            if (apikey.length == 0) {
                Buff.alert({
                    title: i18n("prompt"),
                    message: i18n("clear_the_api_key_after"),
                    confirmText: i18n("confirm_clear"),
                    success: action
                })
            } else {
                action()
            }
        });
        $("#steam-bind").click(function() {
            Buff.alert({
                title: i18n("access_to_the_steam_encounters"),
                message: i18n("recommended_use_of_the_netease"),
                hideCancel: true,
                confirmText: i18n("i_know"),
                rememberDismiss: "steam_network_error",
                extraClasses: "steam_network",
                success: function() {}
            });
            var url = "/account/login/steam?back_url=/account/steam_bind/finish";
            window.open(url, "_blank", "width=800,height=800");
            if (_checkLoginTask == null) {
                _checkLoginTask = setInterval(function() {
                    checkLoginStatus()
                }, 200)
            }
        });
        var handleUnbindVerificationResult = function() {
            var cookie = getCookie("unbind_steam_result");
            if (!cookie) {
                setTimeout(handleUnbindVerificationResult, 200);
                return
            }
            if ($(".popup.steam_network").is(":visible")) {
                Popup.hide()
            }
            removeCookie("unbind_steam_result");
            var unbind_result = JSON.parse(cookie);
            if (!unbind_result.success) {
                if (unbind_result.message) {
                    Buff.toast(unbind_result.message, {
                        type: "error"
                    })
                }
                return
            }
            var send_authcode = function(callback) {
                sendRequest("/account/api/unbind_steam/send_authcode", {
                    method: "POST",
                    dataType: "json",
                    showLoading: false,
                    success: function() {
                        if (callback) {
                            callback()
                        }
                    }
                })
            };
            $(".step-line-12").addClass("on");
            $(".step-2").addClass("on");
            $(".guide-desc-1").hide();
            $(".guide-desc-2").show();
            Popup.hide();
            bindCard.show_authcode_popup({
                send_authcode_function: send_authcode,
                verify_authcode_function: function(authcode, callback) {
                    sendRequest("/account/api/unbind_steam/verify_authcode", {
                        method: "POST",
                        dataType: "json",
                        data: {
                            authcode: authcode
                        },
                        success: function(data) {
                            if (data.code !== "OK") {
                                Buff.toast(data.error, {
                                    type: "error"
                                })
                            } else {
                                if (callback) {
                                    callback()
                                }
                                $(".step-line-23").addClass("on");
                                $(".step-3").addClass("on");
                                $(".guide-desc-2").hide();
                                $(".guide-desc-success").show();
                                Popup.show("j_popup_unbind")
                            }
                        }
                    })
                },
                mobile: $("#mobile").text(),
                authcode_length: 4,
                popup_id: "j_popup_unbind"
            });
            send_authcode()
        };
        var unbindSteamOpenidVerify = function() {
            Buff.alert({
                title: i18n("access_to_the_steam_encounters"),
                message: i18n("recommended_use_of_the_netease"),
                hideCancel: true,
                confirmText: i18n("i_know"),
                rememberDismiss: "steam_network_error",
                extraClasses: "steam_network",
                success: function() {}
            });
            var url = "/account/unbind_steam/openid_login";
            window.open(url, "_blank", "width=800,height=800");
            setTimeout(function() {
                handleUnbindVerificationResult()
            }, 200)
        };
        $("#steam-unbind").click(function() {
            sendRequest("/account/api/unbind_steam/check", {
                method: "GET",
                dataType: "json",
                success: function(data) {
                    if (data.code !== "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        return
                    }
                    Popup.show("j_popup_unbind");
                    $("#btn-verify-steam").on("click", function() {
                        unbindSteamOpenidVerify()
                    })
                }
            })
        });
        $("#user-prefer-allow_buyer_bargain").change(function() {
            var allow_buyer_bargain = $(this).attr("value") == "allow" ? "true" : "false";
            sendRequest("/account/api/prefer/allow_buyer_bargain", {
                method: "POST",
                data: {
                    allow_buyer_bargain: allow_buyer_bargain
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        });
        $("#user-prefer-allow_alipay").change(function() {
            var allow_alipay = $(this).attr("value") == "allow" ? "true" : "false";
            if (allow_alipay == "false") {
                if ($("#user-prefer-allow_epay span.on").attr("value") != "allow") {
                    Buff.toast(i18n("must_allow_epay_or_alipay"), {
                        type: "error"
                    });
                    $(this).find("span").toggleClass("on");
                    return
                }
            }
            sendRequest("/account/api/prefer/allow_alipay", {
                method: "POST",
                data: {
                    allow_alipay: allow_alipay
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        $("#user-prefer-allow_alipay span").toggleClass("on")
                    }
                }
            })
        });
        $("#user-prefer-allow_epay").change(function() {
            var allow_epay = $(this).attr("value") == "allow" ? "true" : "false";
            if (allow_epay == "false") {
                if ($("#user-prefer-allow_alipay span.on").attr("value") != "allow") {
                    Buff.toast(i18n("must_allow_epay_or_alipay"), {
                        type: "error"
                    });
                    $(this).find("span").toggleClass("on");
                    return
                }
            }
            sendRequest("/account/api/prefer/allow_epay", {
                method: "POST",
                data: {
                    allow_epay: allow_epay
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        $("#user-prefer-allow_epay span").toggleClass("on")
                    }
                }
            })
        });
        $("#user-prefer-allow_shop_display").change(function() {
            var allow_shop_display = $(this).attr("value") == "allow" ? "true" : "false";
            sendRequest("/account/api/prefer/allow_shop_display", {
                method: "POST",
                data: {
                    allow_shop_display: allow_shop_display
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        $("#user-prefer-allow_shop_display span").toggleClass("on");
                        $("#user-prefer-allow_shop_display").attr("value", allow_shop_display ? "" : "allow")
                    }
                }
            })
        });
        $("#user-prefer-buff-price-currency").change(function() {
            var buff_price_currency = $(this).attr("value");
            sendRequest("/account/api/prefer/buff_price_currency", {
                method: "POST",
                data: {
                    buff_price_currency: buff_price_currency
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        });
        $("#user-prefer-game-cms-client").change(function() {
            var game_cms_client = $(this).attr("value");
            sendRequest("/account/api/prefer/game_cms_client", {
                method: "POST",
                data: {
                    game_cms_client: game_cms_client
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        });
        $("#user-prefer-force_buyer_send_offer").change(function() {
            var force_buyer_send_offer = $(this).attr("value") == "allow" ? "true" : "false";
            sendRequest("/account/api/prefer/force_buyer_send_offer", {
                method: "POST",
                data: {
                    force_buyer_send_offer: force_buyer_send_offer
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        $("#user-prefer-force_buyer_send_offer span").toggleClass("on");
                        $("#user-prefer-force_buyer_send_offer").attr("value", force_buyer_send_offer ? "" : "allow")
                    }
                }
            })
        });
        $("#user-prefer-allow_sms_notification").change(function() {
            var doChange = function(allow_sms_notification) {
                sendRequest("/account/api/prefer/allow_sms_notification", {
                    method: "POST",
                    data: {
                        allow_sms_notification: allow_sms_notification
                    },
                    dataType: "json",
                    success: function(data) {
                        if (data.code == "OK") {
                            Buff.toast(i18n("set_success"), {
                                type: "success"
                            })
                        } else {
                            Buff.toast(data.error, {
                                type: "error"
                            });
                            $("#user-prefer-allow_sms_notification span").toggleClass("on");
                            $("#user-prefer-allow_sms_notification").attr("value", allow_sms_notification ? "" : "allow")
                        }
                    }
                })
            };
            var allow_sms_notification = $(this).attr("value") == "allow" ? "true" : "false";
            if (allow_sms_notification == "false") {
                Buff.alert({
                    title: i18n("prompt"),
                    message: i18n("disable_sms_notification_alert"),
                    hideCancel: true,
                    success: function() {
                        doChange(allow_sms_notification)
                    },
                    onClose: function() {
                        $("#user-prefer-allow_sms_notification span").addClass("on");
                        $("#user-prefer-allow_sms_notification").attr("value", "allow")
                    }
                })
            } else {
                doChange(allow_sms_notification)
            }
        });
        $("#user-prefer-inventory-price").change(function() {
            var inventory_price = $(this).attr("value");
            sendRequest("/account/api/prefer/inventory_price", {
                method: "POST",
                data: {
                    inventory_price: inventory_price
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        });
        $("#user-prefer-antiscam_level").change(function() {
            var doChange = function(antiscam_level) {
                sendRequest("/account/api/prefer/antiscam_level", {
                    method: "POST",
                    data: {
                        antiscam_level: antiscam_level
                    },
                    dataType: "json",
                    success: function(data) {
                        if (data.code == "OK") {
                            Buff.toast(i18n("set_success"), {
                                type: "success"
                            })
                        } else {
                            Buff.toast(data.error, {
                                type: "error"
                            })
                        }
                    }
                })
            };
            var antiscam_level = parseInt($(this).attr("value"));
            if (antiscam_level == 1) {
                Buff.alert({
                    title: i18n("prompt"),
                    message: i18n("disable_antiscam"),
                    hideCancel: true,
                    success: function() {
                        doChange(antiscam_level)
                    }
                })
            } else {
                doChange(antiscam_level)
            }
        });
        $("#user-prefer-allow_auto_remark").change(function() {
            var doChange = function(allow_auto_remark) {
                sendRequest("/account/api/prefer/allow_auto_remark", {
                    method: "POST",
                    data: {
                        allow_auto_remark: allow_auto_remark
                    },
                    dataType: "json",
                    success: function(data) {
                        if (data.code == "OK") {
                            Buff.toast(i18n("set_success"), {
                                type: "success"
                            })
                        } else {
                            Buff.toast(data.error, {
                                type: "error"
                            });
                            $("#user-prefer-allow_auto_remark span").toggleClass("on");
                            $("#user-prefer-allow_auto_remark").attr("value", allow_auto_remark ? "" : "allow")
                        }
                    }
                })
            };
            var allow_auto_remark = $(this).attr("value") == "allow" ? "true" : "false";
            doChange(allow_auto_remark)
        });
        $(".Btn_realname_cert").click(function() {
            bindCard.show_cert_popup(realname, function() {
                document.location.reload()
            })
        })
    };
    var showWechatPopup = function() {
        if (!g.user) {
            loginModule.showLogin();
            return
        }
        Popup.show("j_popup_weixin");
        var timer = null;
        var fetchCode = function() {
            sendRequest("/account/api/bind_wechat/get_dynamic_code", {
                method: "GET",
                showLoading: false,
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(i18n("to_obtain_the_dynamic_code"), {
                            type: "error"
                        });
                        return
                    }
                    $("#j_progress").width("0%");
                    var code = data.data.code;
                    var html = "";
                    code.split("").map(function(elem) {
                        html = html + '<span class="flipInX">' + elem + "</span>"
                    });
                    $("#j_qrcode").html(html);
                    var progress = 0;
                    timer = setInterval(function() {
                        var step = 100 / data.data.refresh;
                        progress += step;
                        $("#j_progress").width(progress + "%");
                        if (progress >= 100) {
                            clearInterval(timer);
                            fetchCode()
                        }
                    }, 1e3);
                    $("#j_popup_weixin .popup-close").off("click").click(function() {
                        Popup.hide();
                        clearInterval(timer)
                    })
                }
            })
        };
        fetchCode()
    };
    return {
        init: init,
        showWechatPopup: showWechatPopup
    }
};
var guideManager = function(backUrl) {
    var backUrl = backUrl || "";
    var should_polling = false;
    var html = '<div class="popup popup_guide" id="j_popup_guide" style="width:600px;">    <a class="popup-close" href="javascript:;" onclick="window.location.reload()">×</a>    <div class="popup-header"><h2>' + i18n("set_the_boot") + '</h2></div>    <p class="popup-tip c_Green">' + i18n("in_order_to_your_funds") + '</p>    <div class="popup-cont" style="min-height:410px;">        <div class="guide-steps">        </div>        <div class="guide-desc">        </div>    </div></div>';
    var showStep = function(steamid, trade_url) {
        var step_html = "";
        if (typeof steamid == "string" && steamid.length > 0) {
            step_html += '            <div class="step-1">                <i class="icon icon_success_big"></i>                <h5>' + i18n("binding_steam") + '</h5>            </div>            <div class="step-line on"></div>';
            should_polling = false
        } else {
            step_html += '            <div class="step-1">                <span>1</span>                <h5>' + i18n("binding_steam") + '</h5>            </div>            <div class="step-line"></div>';
            should_polling = true
        }
        if (typeof trade_url == "string" && trade_url.length > 0) {
            step_html += '            <div class="step-1">                <i class="icon icon_success_big"></i>                <h5>' + i18n("set_up_trading_links") + "</h5>            </div>"
        } else {
            step_html += '            <div class="step-1">                <span>2</span>                <h5>' + i18n("set_up_trading_links") + "</h5>            </div>"
        }
        step_html += '<p class="clear"></p>';
        $("#j_popup_guide .guide-steps").html(step_html)
    };
    var showCont = function(steamid, trade_url) {
        var cont_html = "";
        if (typeof steamid != "string" || steamid.length == 0) {
            cont_html = '            <div class="guide-block">                <p>' + i18n("binding_steam_before_you_can") + '</p>                <p><a href="javascript:;" data-url="/account/login/steam?back_url=/account/steam_bind/finish" target="_blank" class="i_Btn go_to_steam">' + i18n("to_steam") + '</a></p>            </div>            <a href="javascript:;" onclick="window.location.reload()">' + i18n("skip_maybe_next_time") + "</a></p>"
        } else if (typeof trade_url != "string" || trade_url.length == 0) {
            cont_html = '            <div class="guide-block trade-url">                <p class="t_Left"><span class="l_Right"><a class="go_to_steam" href="javascript:;" data-url="https://steamcommunity.com/my/tradeoffers/privacy#trade_offer_access_url" data-size="1200*800" target="_blank">' + i18n("get_steam_trading_link") + '</a><i class="icon icon_arr_right_small"></i></span>' + i18n("binding_transaction_link_the_immediate") + '</p>                <p class="t_Left"><input type="text" name="trade_url" class="i_Text" placeholder="' + i18n("please_enter_your_steam_trade") + '"><a href="javascript:;" class="i_Btn">' + i18n("save") + '</a></p>            </div>            <p class="t_Right">            <a href="javascript:;" onclick="window.location.reload()">' + i18n("skip_maybe_next_time") + "</a></p>"
        }
        if (cont_html.length == 0) {
            cont_html = '            <div class="guide-block guide-block_success">                <p style="line-height:70px;">' + i18n("congratulations_to_you!_welcome_to") + "</p>            </div>";
            if (backUrl.length > 0) {
                cont_html += '<p><a href="' + backUrl + '" class="i_Btn i_Btn_long" onclick="window.location.reload()">' + i18n("complete") + "</a></p>"
            } else {
                cont_html += '<p><a href="/market/steam_inventory" class="i_Btn i_Btn_long">' + i18n("view_my_steam_inventory") + "</a></p>"
            }
        }
        $("#j_popup_guide .guide-desc").html(cont_html)
    };
    var getUserInfo = function(callback) {
        sendRequest("/account/api/user/info", {
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code == "OK") {
                    callback(data.data)
                } else {
                    Buff.toast(data.error)
                }
            }
        })
    };
    var init = function() {
        $("body").append(html);
        $(document).on("click", ".trade-url .i_Btn", function() {
            var tradeUrl = $("input[name=trade_url]").val();
            if (!tradeUrl) {
                Buff.toast(i18n("please_fill_out_the_trading"));
                $("input[name=trade_url]").addClass("i_Text_error");
                return
            }
            var validPrefix = "https://steamcommunity.com/tradeoffer/new/?";
            if (tradeUrl.substr(0, validPrefix.length) !== validPrefix) {
                Buff.toast(i18n("trading_link_format_error"));
                $("input[name=trade_url]").addClass("i_Text_error");
                return
            }
            $("input[name=trade_url]").removeClass("i_Text_error");
            sendRequest("/api/market/steam/trade_url", {
                method: "POST",
                dataType: "json",
                data: {
                    trade_url: tradeUrl
                },
                showLoading: true,
                success: function(data) {
                    if (data.code === "OK") {
                        $("input[name=trade_url]").removeClass("i_Text_error");
                        sendRequest("/account/api/user/info", {
                            method: "GET",
                            showLoading: false,
                            showError: false,
                            success: function(data) {
                                if (data.code != "OK") {
                                    Buff.toast(data.error);
                                    return
                                } else {
                                    showStep(data.data.steamid, data.data.trade_url);
                                    showCont(data.data.steamid, data.data.trade_url)
                                }
                            }
                        })
                    } else {
                        $("input[name=trade_url]").addClass("i_Text_error");
                        Buff.toast(i18n("set_to_fail") + (data.error || data.code))
                    }
                },
                error: function() {
                    $("input[name=trade_url]").addClass("i_Text_error");
                    Buff.toast(i18n("settings_failed_please_try_again"))
                }
            })
        })
    };
    var bindConfirm = function(steam_id, authcode, callback) {
        var params = {
            steam_id: steam_id
        };
        if (authcode) {
            params.authcode = authcode
        }
        sendRequest("/account/api/bind_steam/confirm", {
            method: "POST",
            dataType: "json",
            data: params,
            success: function(data) {
                if (data.code == "OK") {
                    if (callback)
                        callback();
                    showStep(steam_id, null);
                    showCont(steam_id, null)
                } else {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    if ($(".popup.steam_network").is(":visible")) {
                        Popup.hide()
                    }
                }
            }
        })
    };
    var generateAuthcodePopup = function() {
        if ($("#j_popup_bind_authcode").length == 0) {
            var html = '    <div class="popup" id="j_popup_bind_authcode">        <a class="popup-close" href="javascript:;">×</a>        <div class="popup-cont">            <h2>' + i18n("enter_the_verification_code") + '</h2>            <div class="popup-desc">                <p>' + i18n("please_do_the_safety_confirmation") + '<span id="mobile"></span>' + i18n("the_phone_receives_the_verification") + '</p>                <p class="t_Center">                    <input type="text" class="i_Text" name="authcode" placeholder="' + i18n("please_enter_the_verification_code") + '" size="38">                </p>            </div>        </div>        <div class="popup-btns">            <a href="javascript:;" class="i_Btn i_Btn_sub i_Btn_disabled" id="resend_authcode">' + i18n("get_the_verification_code") + '</a><a href="javascript:;" class="i_Btn i_Btn_main i_Btn_disabled" id="verify_authcode">' + i18n("ok") + "</a>        </div>    </div>";
            $("body").append($(html))
        }
    };
    var polling = function() {
        if (should_polling) {
            var steam_info = getCookie("steam_info_to_bind");
            var msg = getCookie("bind_steam_err_msg");
            if (steam_info) {
                removeCookie("steam_info_to_bind");
                if ($(".popup.steam_network").is(":visible")) {
                    Popup.hide()
                }
                var split_info = steam_info.split(":");
                var steam_id = split_info[0];
                var steam_nickname = split_info[1];
                var need_authcode = parseInt(split_info[2] || "0");
                var blurred_mobile = split_info[3] || "";
                Buff.alert({
                    title: i18n("binding_acknowledgment"),
                    message: i18n("acknowledgment_is_bound_to_the") + steam_nickname + "<br>Steam ID：" + steam_id,
                    success: function() {
                        if (!need_authcode) {
                            bindConfirm(steam_id)
                        } else {
                            generateAuthcodePopup();
                            var send_authcode = function(callback) {
                                sendRequest("/account/api/bind_steam/send_authcode", {
                                    method: "POST",
                                    dataType: "json",
                                    showLoading: false,
                                    success: function() {
                                        if (callback) {
                                            callback()
                                        }
                                    }
                                })
                            };
                            bindCard.show_authcode_popup({
                                send_authcode_function: send_authcode,
                                verify_authcode_function: function(authcode, callback) {
                                    bindConfirm(steam_id, authcode, callback)
                                },
                                mobile: blurred_mobile,
                                authcode_length: 4,
                                popup_id: "j_popup_bind_authcode"
                            });
                            send_authcode()
                        }
                    }
                })
            } else if (msg) {
                removeCookie("bind_steam_err_msg");
                if ($(".popup.steam_network").is(":visible")) {
                    Popup.hide()
                }
                Buff.toast(msg, {
                    type: "error"
                })
            }
        }
    };
    var show = function(info) {
        Popup.hide();
        var steamid = info.steamid || null;
        var trade_url = info.trade_url || "";
        Popup.show("j_popup_guide");
        showStep(steamid, trade_url);
        showCont(steamid, trade_url);
        setInterval(polling, 200)
    };
    var shouldShow = function(info) {
        if (typeof info.steamid != "string" || info.steamid.length == 0)
            return true;
        if (typeof info.trade_url != "string" || info.trade_url.length == 0)
            return true;
        return false
    };
    return {
        init: init,
        show: show,
        shouldShow: shouldShow,
        getUserInfo: getUserInfo
    }
};
var steamVerifyManager = function(backUrl) {
    var backUrl = backUrl || "";
    var should_polling = false;
    var html = '    <div class="popup popup_guide" id="j_popup_guide" style="width:600px; height: 400px;">    <div class="popup-header"><h2>' + i18n("authentication") + '</h2></div>    <p class="popup-tip c_Green">' + i18n("for_the_protection_of_your") + '</p>    <div class="popup-cont" style="min-height:410px;">        <div class="guide-desc">            <div class="guide-block">                <p>' + i18n("your_phone_account_through_a") + '</p>                <p><a href="javascript:;" data-url="/account/steam/openid_login?back_url=/account/steam/openid_verifier" target="_blank" class="i_Btn go_to_steam">' + i18n("verify") + "</a></p>            </div>        </div>    </div></div>";
    var init = function() {
        $("body").append(html)
    };
    var pollVerifyResult = function() {
        var cookie = getCookie("steam_verify_result");
        if (!cookie) {
            setTimeout(function() {
                pollVerifyResult()
            }, 200);
            return
        }
        removeCookie("steam_verify_result");
        var result = JSON.parse(cookie);
        if (result.success) {
            Buff.toast(result.message, {
                type: "success"
            });
            setTimeout(function() {
                window.location.reload()
            }, 1e3)
        } else {
            if (result.message) {
                Buff.toast(result.message, {
                    type: "error"
                })
            }
            setTimeout(function() {
                pollVerifyResult()
            }, 200)
        }
    };
    var show = function(info) {
        Popup.hide();
        removeCookie("steam_verify_result");
        Popup.show("j_popup_guide");
        setTimeout(function() {
            pollVerifyResult()
        }, 200)
    };
    var shouldShow = function(info) {
        return info.is_need_steam_verify && info.login_from == 1
    };
    return {
        init: init,
        show: show,
        shouldShow: shouldShow
    }
};
var authcodeVerifyManager = function(popup_id) {
    var show = function() {
        Popup.hide();
        Popup.show(popup_id)
    };
    var clear = function() {
        Popup.hide();
        $("#" + popup_id).remove()
    };
    var countdownHandler = undefined;
    var wait = 0;
    function countdown(o, total_wait_time) {
        if (total_wait_time || wait > 0) {
            if (total_wait_time) {
                wait = total_wait_time
            } else {
                wait--
            }
            o.addClass("i_Btn_disabled");
            o.html(i18n("resend") + "<small>(" + wait + ")</small>");
            countdownHandler = setTimeout(function() {
                countdown(o)
            }, 1e3)
        } else if (wait == 0) {
            o.removeClass("i_Btn_disabled");
            o.text(i18n("get_the_verification_code"));
            countdownHandler = undefined
        }
    }
    var sendAuthcode = function(send_api, params, $btn_send) {
        if (!params) {
            params = {}
        }
        $btn_send.text(i18n("has_been_sent")).addClass("i_Btn_disabled");
        sendRequest(send_api, {
            method: "POST",
            dataType: "json",
            data: params,
            showLoading: false,
            success: function(data) {
                if (data.code == "OK") {
                    Buff.toast(i18n("sent_successfully_please_note_the"), {
                        type: "success"
                    });
                    if (countdownHandler === undefined) {
                        countdown($btn_send, 60)
                    }
                } else {
                    Buff.toast(data.error || data.msg || i18n("error_code") + data.code, {
                        type: "error"
                    });
                    $btn_send.removeClass("i_Btn_disabled").text(i18n("get_the_verification_code"))
                }
            }
        })
    };
    var verifyAuthcode = function(verify_api, authcode, params, callback) {
        if (!authcode || authcode.length != 4) {
            Buff.toast(i18n("the_verification_code_is_incorrect"));
            return
        }
        if (!params) {
            params = {
                authcode: authcode
            }
        } else {
            params["authcode"] = authcode
        }
        sendRequest(verify_api, {
            method: "POST",
            dataType: "json",
            data: params,
            success: function(data) {
                if (data.code == "OK") {
                    clear();
                    if (callback) {
                        callback(data.data)
                    }
                } else {
                    Buff.toast(data.error || data.msg || i18n("error_code") + data.code, {
                        type: "error"
                    })
                }
            }
        })
    };
    return {
        show: show,
        clear: clear,
        sendAuthcode: sendAuthcode,
        verifyAuthcode: verifyAuthcode
    }
};
var commonAuthcodeVerifyManager = function(mobile, send_url, send_params, verify_url, verify_params, verify_callback) {
    var html = '        <div class="popup popup_guide" id="j_popup_common_authcode_verify" style="width:600px;">            <a class="popup-close" href="javascript:;">×</a>            <div class="popup-header"><h2>' + i18n("authentication") + '</h2></div>            <p class="popup-tip c_Green">' + i18n("urs_password_login_need_verify") + '</p>            <div class="popup-cont">                <div class="guide-desc" style="display:;">                    <div class="guide-block">                        <p class="c_Gray f_12px">' + i18n("please_enter") + mobile + i18n("receive_sms_verification_code") + '</p>                        <p class="t_Left">                            <input type="text" name="authcode" class="i_Text" placeholder="' + i18n("enter_the_verification_code") + '">                            <a id="btn-common-send-authcode" href="#" class="i_Btn i_Btn_hollow" onclick="">                                ' + i18n("get_the_verification_code") + '                            </a>                        </p>                        \x3c!-- 发送后给i_Btn加i_Btn_disabled，如下示例： --\x3e                        \x3c!--                        <p class="t_Left"><input type="text" class="i_Text" placeholder="' + i18n("enter_the_verification_code") + '"><a href="#" class="i_Btn i_Btn_hollow i_Btn_disabled">' + i18n("has_been_sent") + '(29)</a></p>                        --\x3e                    </div>                    <p><a id="btn-common-verify-authcode" href="javascript:;" class="i_Btn i_Btn_long">' + i18n("complete") + "</a></p>                </div>            </div>        </div>    ";
    var popup_id = "j_popup_common_authcode_verify";
    var manager = authcodeVerifyManager(popup_id);
    var init = function() {
        $("body").append(html);
        $("#" + popup_id + " .popup-close").click(function() {
            manager.clear()
        });
        var $btn_send = $("#btn-common-send-authcode");
        $btn_send.click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            manager.sendAuthcode(send_url, send_params, $btn_send)
        });
        $("#btn-common-verify-authcode").click(function() {
            var authcode = $("#" + popup_id + " input[name=authcode]").val();
            verify_callback = verify_callback || function() {
                Buff.toast(i18n("the_validation_is_successful"), {
                    type: "success"
                });
                window.location.reload()
            }
            ;
            manager.verifyAuthcode(verify_url, authcode, verify_params, verify_callback)
        });
        manager.show()
    };
    return {
        init: init
    }
};
var loggedInFromSteamVerifyManager = function(mobile) {
    var html = '        <div class="popup popup_guide" id="j_popup_logged_in_from_steam_verify" style="width:600px;">            <a class="popup-close" href="javascript:;" onclick="Popup.hide()">×</a>            <div class="popup-header"><h2>' + i18n("authentication") + '</h2></div>            <p class="popup-tip c_Green">' + i18n("detected_you_are_using_steam") + '</p>            <div class="popup-cont">                <div class="guide-desc" style="display:;">                    <div class="guide-block">                        <p class="c_Gray f_12px">' + i18n("please_enter") + mobile + i18n("receive_sms_verification_code") + '</p>                        <p class="t_Left">                            <input id="input-unfrozen-authcode" type="text" class="i_Text" placeholder="' + i18n("enter_the_verification_code") + '">                            <a id="btn-unfrozen-send" href="#" class="i_Btn i_Btn_hollow" onclick="">                                ' + i18n("get_the_verification_code") + '                            </a>                        </p>                        \x3c!-- 发送后给i_Btn加i_Btn_disabled，如下示例： --\x3e                        \x3c!--                        <p class="t_Left"><input type="text" class="i_Text" placeholder="' + i18n("enter_the_verification_code") + '"><a href="#" class="i_Btn i_Btn_hollow i_Btn_disabled">' + i18n("has_been_sent") + '(29)</a></p>                        --\x3e                    </div>                    <p><a id="btn-unfrozen-verify" href="javascript:;" class="i_Btn i_Btn_long">' + i18n("complete") + '</a></p>                    <ul class="c_Gray f_12px t_Left f_line24" >                        <li>' + i18n("the_phone_number_has_been") + '<a href="/user-center/feedback/" target="_blank" class="c_Blue">' + i18n("artificial_assist") + "</a></li>                    </ul>                </div>            </div>        </div>    ";
    var popup_id = "j_popup_logged_in_from_steam_verify";
    var manager = authcodeVerifyManager(popup_id);
    var init = function() {
        $("body").append(html);
        $("#" + popup_id + " .popup-close").click(function() {
            manager.clear()
        });
        var $btn_send = $("#btn-unfrozen-send");
        $btn_send.click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            manager.sendAuthcode("/account/api/logged_in_from_steam/send_authcode", null, $btn_send)
        });
        $("#btn-unfrozen-verify").click(function() {
            var authcode = $("#input-unfrozen-authcode").val();
            manager.verifyAuthcode("/account/api/logged_in_from_steam/verify_authcode", authcode, null, function() {
                Buff.toast(i18n("the_validation_is_successful"), {
                    type: "success"
                });
                window.location.reload()
            })
        });
        manager.show()
    };
    return {
        init: init
    }
};
var ursLoginMobileSecondaryVerifyManager = function(mobile, verify_key, callback) {
    var html = '        <div class="popup popup_guide" id="j_popup_login_mobile_verify" style="width:600px;">            <a class="popup-close" href="javascript:;">×</a>            <div class="popup-header"><h2>' + i18n("authentication") + '</h2></div>            <p class="popup-tip c_Green">' + i18n("urs_password_login_need_verify") + '</p>            <div class="popup-cont">                <div class="guide-desc" style="display:;">                    <div class="guide-block">                        <p class="c_Gray f_12px">' + i18n("please_enter") + mobile + i18n("receive_sms_verification_code") + '</p>                        <p class="t_Left">                            <input id="input-login-authcode" type="text" class="i_Text" placeholder="' + i18n("enter_the_verification_code") + '">                            <a id="btn-login-send" href="#" class="i_Btn i_Btn_hollow" onclick="">                                ' + i18n("get_the_verification_code") + '                            </a>                        </p>                        \x3c!-- 发送后给i_Btn加i_Btn_disabled，如下示例： --\x3e                        \x3c!--                        <p class="t_Left"><input type="text" class="i_Text" placeholder="' + i18n("enter_the_verification_code") + '"><a href="#" class="i_Btn i_Btn_hollow i_Btn_disabled">' + i18n("has_been_sent") + '(29)</a></p>                        --\x3e                    </div>                    <p><a id="btn-login-verify" href="javascript:;" class="i_Btn i_Btn_long">' + i18n("complete") + "</a></p>                </div>            </div>        </div>    ";
    var popup_id = "j_popup_login_mobile_verify";
    var manager = authcodeVerifyManager(popup_id);
    var init = function() {
        $("body").append(html);
        $("#" + popup_id + " .popup-close").click(function() {
            manager.clear()
        });
        var $btn_send = $("#btn-login-send");
        $btn_send.click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            manager.sendAuthcode("/account/api/urs_password_login/send_authcode", {
                verify_key: verify_key
            }, $btn_send)
        });
        $("#btn-login-verify").click(function() {
            var authcode = $("#input-login-authcode").val();
            manager.verifyAuthcode("/account/api/urs_password_login/verify_authcode", authcode, {
                verify_key: verify_key
            }, function() {
                if (callback) {
                    callback(null, verify_key)
                }
            })
        });
        manager.show()
    };
    return {
        init: init
    }
};
var unfrozenVerifyManager = function(mobile) {
    var html = '        <div class="popup popup_guide" id="j_popup_unfrozen_mobile_verify" style="width:600px;">            <a class="popup-close" href="javascript:;" onclick="Popup.hide()">×</a>            <div class="popup-header"><h2>' + i18n("authentication") + '</h2></div>            <p class="popup-tip c_Green">' + i18n("your_mobile_phone_account_occurs") + '</p>            <div class="popup-cont">                <div class="guide-desc" style="display:;">                    <div class="guide-block">                        <p class="c_Gray f_12px">' + i18n("please_enter") + mobile + i18n("receive_sms_verification_code") + '</p>                        <p class="t_Left">                            <input id="input-unfrozen-authcode" type="text" class="i_Text" placeholder="' + i18n("enter_the_verification_code") + '">                            <a id="btn-unfrozen-send" href="#" class="i_Btn i_Btn_hollow" onclick="">                                ' + i18n("get_the_verification_code") + '                            </a>                        </p>                        \x3c!-- 发送后给i_Btn加i_Btn_disabled，如下示例： --\x3e                        \x3c!--                        <p class="t_Left"><input type="text" class="i_Text" placeholder="' + i18n("enter_the_verification_code") + '"><a href="#" class="i_Btn i_Btn_hollow i_Btn_disabled">' + i18n("has_been_sent") + '(29)</a></p>                        --\x3e                    </div>                    <p><a id="btn-unfrozen-verify" href="javascript:;" class="i_Btn i_Btn_long">' + i18n("complete") + '</a></p>                    <ul class="c_Gray f_12px t_Left f_line24" >                        <li>' + i18n("not_my_phone_number_please") + '<a href="/user-center/feedback/" target="_blank" class="c_Blue">' + i18n("artificial_assist") + "</a></li>                    </ul>                </div>            </div>        </div>    ";
    var popup_id = "j_popup_unfrozen_mobile_verify";
    var manager = authcodeVerifyManager(popup_id);
    var init = function() {
        $("body").append(html);
        $("#" + popup_id + " .popup-close").click(function() {
            manager.clear()
        });
        var $btn_send = $("#btn-unfrozen-send");
        $btn_send.click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            manager.sendAuthcode("/account/api/unfrozen/send_authcode", null, $btn_send)
        });
        $("#btn-unfrozen-verify").click(function() {
            var authcode = $("#input-unfrozen-authcode").val();
            manager.verifyAuthcode("/account/api/unfrozen/verify_authcode", authcode, null, function() {
                Buff.toast(i18n("the_validation_is_successful"), {
                    type: "success"
                });
                window.location.reload()
            })
        });
        manager.show()
    };
    return {
        init: init
    }
};
var bookmark = function() {
    var instance, cache_data = {}, init = function() {
        if (instance)
            return;
        $(document).on("click", ".add-bookmark", function() {
            var that = this;
            var target_type = $(that).data("target-type");
            var target_id = $(that).data("target-id");
            sendRequest("/account/api/add_bookmark", {
                method: "PUT",
                data: {
                    target_type: target_type,
                    target_id: target_id
                },
                showLoading: false,
                success: function(data) {
                    if (data.code !== "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        return
                    }
                    cache_data[target_type + "_" + target_id] = "delete";
                    $(".add-bookmark[data-target-type=" + target_type + "][data-target-id=" + target_id + "]").hide();
                    $(".delete-bookmark[data-target-type=" + target_type + "][data-target-id=" + target_id + "]").show()
                }
            })
        });
        $(document).on("click", ".delete-bookmark", function() {
            var that = this;
            var target_type = $(that).data("target-type");
            var target_id = $(that).data("target-id");
            var needConfirm = $(that).data("confirm");
            var func = function() {
                sendRequest("/account/api/delete_bookmark", {
                    method: "DELETE",
                    data: {
                        target_type: target_type,
                        target_id: target_id
                    },
                    showLoading: false,
                    success: function(data) {
                        if (data.code !== "OK") {
                            Buff.toast(data.error, {
                                type: "error"
                            });
                            return
                        }
                        cache_data[target_type + "_" + target_id] = "add";
                        $(".add-bookmark[data-target-type=" + target_type + "][data-target-id=" + target_id + "]").show();
                        $(".delete-bookmark[data-target-type=" + target_type + "][data-target-id=" + target_id + "]").hide();
                        if (needConfirm) {
                            window.location.reload()
                        }
                    }
                })
            };
            if (needConfirm) {
                Buff.alert({
                    title: i18n("out_collection"),
                    message: i18n("determined_to_be_removed_from"),
                    success: function() {
                        func()
                    }
                })
            } else {
                func()
            }
        })
    };
    updateView = function() {
        Object.keys(cache_data).map(function(key, index) {
            var state = cache_data[key]
              , arr = key.split("_")
              , target_type = arr[0]
              , target_id = arr[1];
            if (state == "add") {
                $(".add-bookmark[data-target-type=" + target_type + "][data-target-id=" + target_id + "]").show();
                $(".delete-bookmark[data-target-type=" + target_type + "][data-target-id=" + target_id + "]").hide()
            } else if (state == "delete") {
                $(".add-bookmark[data-target-type=" + target_type + "][data-target-id=" + target_id + "]").hide();
                $(".delete-bookmark[data-target-type=" + target_type + "][data-target-id=" + target_id + "]").show()
            }
        })
    }
    ;
    setCacheData = function(target_type, target_id, bookmarked) {
        cache_data[target_type + "_" + target_id] = bookmarked ? "delete" : "add"
    }
    ;
    return function() {
        if (!instance) {
            init();
            instance = {
                init: init,
                updateView: updateView,
                setCacheData: setCacheData
            }
        }
        return instance
    }
}();
var normalBuy = function(user_id) {
    var current_user_id = user_id;
    var game = g.game;
    var allow_tradable_cooldown = 0;
    var wait_recharge_handler;
    var WX_PAGE = 6;
    var ALIPAY_PAGE_PCREDIT = 10;
    var pay_data = {};
    var show_wx_pay_qrcode = function(bill_order_id, price) {
        sendRequest("/api/market/bill_order/wx_pay_qrcode", {
            method: "GET",
            data: {
                bill_order_id: bill_order_id
            },
            dataType: "json",
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    return
                }
                $("#j_popup_wx").remove();
                var html = template_render("wx_pay_pat", {
                    price: price
                });
                $("body").append(html);
                $("#wx-pay-qrcode").html("");
                new QRCode(document.getElementById("wx-pay-qrcode"),{
                    text: data.data.url,
                    width: 140,
                    height: 140
                });
                $("#wx-pay-qrcode").attr("title", "");
                update_pay_remain_time(data.data.pay_expire_timeout);
                $("#j_popup_wx .popup-close").click(function() {
                    Popup.hide();
                    if ($("#j_popup_wx").hasClass("expired"))
                        return;
                    Buff.alert({
                        title: i18n("waiting_for_payment"),
                        message: i18n("you_havent_successfully_paid_the"),
                        confirmText: i18n("continue_to_pay"),
                        cancelText: i18n("confirm_leave"),
                        success: function() {
                            Popup.show("j_popup_wx")
                        },
                        cancel: function() {
                            window.location.reload()
                        },
                        onClose: function() {
                            window.location.reload()
                        }
                    })
                });
                Popup.hide();
                Popup.show("j_popup_wx");
                goods_after_pay(bill_order_id, WX_PAGE);
                return
            }
        })
    };
    var open_pcredit_pay = function(bill_order_id) {
        sendRequest("/api/market/bill_order/pcredit_page_pay", {
            method: "GET",
            data: {
                bill_order_id: bill_order_id
            },
            dataType: "json",
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    return
                }
                openPageOnNewTab(data.data.elements.url);
                Popup.hide();
                goods_after_pay(bill_order_id, ALIPAY_PAGE_PCREDIT)
            }
        })
    };
    var update_pay_remain_time = function(timeout) {
        var minutes = 0
          , seconds = 0;
        if (timeout > 0) {
            minutes = Math.floor(timeout / 60);
            seconds = timeout % 60
        }
        var text = minutes + i18n("minutes") + seconds + i18n("seconds");
        $("#pay-remain-time").text(text)
    };
    var goods_buy = function() {
        pay_method = pay_data.pay_method;
        sendRequest("/api/market/goods/buy", {
            data: {
                game: game,
                goods_id: pay_data.goods_id,
                sell_order_id: pay_data.sell_order_id,
                price: pay_data.price,
                pay_method: pay_data.pay_method,
                allow_tradable_cooldown: allow_tradable_cooldown,
                token: getParams().token || "",
                cdkey_id: pay_data.cdkey_id
            },
            dataType: "json",
            method: "POST",
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "warning"
                    });
                    return
                }
                bill_order_id = data.data.id;
                if (pay_method == WX_PAGE) {
                    show_wx_pay_qrcode(bill_order_id, data.data.price)
                } else if (pay_method == ALIPAY_PAGE_PCREDIT) {
                    open_pcredit_pay(bill_order_id)
                } else {
                    goods_after_pay(bill_order_id, pay_method)
                }
            },
            error: function() {
                $("#loading-cover").hide();
                Popup.hide();
                Buff.alert({
                    title: i18n("prompt"),
                    message: i18n("the_system_is_busy_please"),
                    hideCancel: true,
                    success: function() {
                        window.location.href = "/market/buy_order/history?game=" + game
                    }
                })
            },
            complete: function(resp) {
                if (resp.responseJSON.code == "Realname Required" || resp.responseJSON.code == "Market Ban Epay Balance" || resp.responseJSON.code == "Seller Realname Required") {
                    $(".pay-btn").removeClass("i_Btn_disabled")
                }
            }
        })
    };
    var notify_buyer_to_send_offer = function(bill_order, callback) {
        sendRequest("/api/market/bill_order/notify_buyer_to_send_offer", {
            method: "POST",
            dataType: "json",
            data: {
                bill_order_id: bill_order.id,
                game: bill_order.game
            },
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    return
                }
                if (callback)
                    callback()
            }
        })
    };
    var goods_after_pay = function(bill_order_id, pay_method) {
        var wait = 0;
        var check_result_reture = false;
        var check_pay_order = function(order_id) {
            sendRequest("/api/market/bill_order/batch/info", {
                data: {
                    bill_orders: order_id
                },
                dataType: "json",
                method: "GET",
                timeout: 2e3,
                showLoading: false,
                showError: false,
                success: function(data) {
                    if (data.code != "OK") {
                        return
                    }
                    if (data.data.items.length != 1) {
                        return
                    }
                    check_result_reture = true;
                    var bill_order = data.data.items[0];
                    if ((bill_order.mode == 2 && bill_order.state == "TO_DELIVER" || bill_order.mode == 5 && bill_order.progress == 305 || bill_order.state == "SUCCESS") && wait_recharge_handler != undefined) {
                        clearInterval(wait_recharge_handler);
                        wait_recharge_handler = undefined;
                        Popup.hide();
                        if (bill_order.mode == 5) {
                            $("#j_popup_payed").remove();
                            var html = template_render("manual_plus_pay_success_pat");
                            $("body").append(html);
                            $("#j_popup_payed #go_to_app,.popup-close").click(function() {
                                Popup.hide();
                                notify_buyer_to_send_offer(bill_order);
                                Buff.toast(i18n("add_in_5_minutes_to"), {
                                    type: "success"
                                });
                                setTimeout(function() {
                                    window.location.reload()
                                }, 3e3)
                            });
                            $("#j_popup_payed #ask_seller").click(function() {
                                Popup.hide();
                                sendRequest("/api/market/bill_order/ask_seller_to_send_offer", {
                                    method: "POST",
                                    dataType: "json",
                                    data: {
                                        bill_orders: [order_id],
                                        game: bill_order.game
                                    },
                                    success: function(data) {
                                        if (data.code != "OK") {
                                            Buff.toast(data.error, {
                                                type: "error"
                                            })
                                        } else if (data.data[order_id] != "OK") {
                                            Buff.toast(data.data[order_id], {
                                                type: "error"
                                            })
                                        } else {
                                            Buff.toast(i18n("please_wait_for_seller_to"), {
                                                type: "success"
                                            })
                                        }
                                        setTimeout(function() {
                                            window.location.reload()
                                        }, 3e3)
                                    }
                                })
                            });
                            Popup.show("j_popup_payed")
                        } else {
                            Buff.alert({
                                type: "success",
                                title: bill_order.mode == 2 ? i18n("the_payment_is_successful") : i18n("buy_success"),
                                message: bill_order.mode == 2 ? i18n("please_wait_for_the_seller") : i18n("please_in_the_backpack_view"),
                                hideCancel: true,
                                success: function() {
                                    window.location.reload()
                                }
                            })
                        }
                    }
                    if (pay_method == WX_PAGE) {
                        if (bill_order.progress == 104 || bill_order.progress == 102 && bill_order.pay_expire_timeout <= 0) {
                            clearInterval(wait_recharge_handler);
                            wait_recharge_handler = undefined;
                            $("#j_popup_wx").addClass("expired");
                            $("#j_popup_wx .popup-cont.paying").hide();
                            $("#j_popup_wx .popup-cont.expired").show()
                        } else if (bill_order.progress == 102) {
                            update_pay_remain_time(bill_order.pay_expire_timeout)
                        }
                    } else if (pay_method == ALIPAY_PAGE_PCREDIT) {
                        if (bill_order.progress == 104 || bill_order.progress == 102 && bill_order.pay_expire_timeout <= 0) {
                            clearInterval(wait_recharge_handler);
                            wait_recharge_handler = undefined;
                            Popup.hide();
                            Buff.alert({
                                title: i18n("prompt"),
                                message: i18n("pay_failed"),
                                hideCancel: true,
                                success: function() {
                                    window.location.reload()
                                }
                            })
                        }
                    }
                },
                error: function() {
                    check_result_reture = true
                }
            })
        };
        if (pay_method != WX_PAGE) {
            Popup.hide();
            Buff.alert({
                title: i18n("payment"),
                message: i18n("please_wait"),
                hideCancel: true,
                hideConfirm: true
            })
        }
        var WAIT_SECOND = pay_method == WX_PAGE || pay_method == ALIPAY_PAGE_PCREDIT ? 300 : 5;
        wait_recharge_handler = setInterval(function() {
            wait += 1;
            if (wait == 1 || wait <= WAIT_SECOND && check_result_reture) {
                check_result_reture = false;
                check_pay_order(bill_order_id)
            } else if (wait > WAIT_SECOND) {
                clearInterval(wait_recharge_handler);
                wait_recharge_handler = undefined;
                Popup.hide();
                Buff.alert({
                    title: i18n("payment"),
                    message: i18n("payment_system_is_busy_please"),
                    hideCancel: true,
                    success: function() {
                        window.location.reload()
                    }
                })
            }
        }, 1e3)
    };
    var goods_buy_resend_authcode = function(bill_order_id) {
        var ret = function(after_send_authcode_function) {
            sendRequest("/api/asset/send_pay_authcode/", {
                data: {
                    bill_order_id: bill_order_id
                },
                dataType: "json",
                method: "POST",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "warning"
                        });
                        return
                    }
                    after_send_authcode_function()
                }
            })
        };
        return ret
    };
    var goods_buy_verify = function(bill_order_id, pay_method) {
        var ret = function(authcode) {
            sendRequest("/api/asset/verify_pay_authcode/", {
                data: {
                    bill_order_id: bill_order_id,
                    authcode: authcode
                },
                dataType: "json",
                method: "POST",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "warning"
                        });
                        return
                    }
                    goods_after_pay(bill_order_id, pay_method)
                }
            })
        };
        return ret
    };
    var buy_check = function(selected_pay_method) {
        sendRequest("/api/market/goods/buy/preview", {
            data: {
                game: game,
                sell_order_id: pay_data.sell_order_id,
                goods_id: pay_data.goods_id,
                price: pay_data.price,
                allow_tradable_cooldown: allow_tradable_cooldown,
                cdkey_id: pay_data.cdkey_id
            },
            dataType: "json",
            method: "GET",
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "warning"
                    });
                    return
                }
                Popup.hide();
                var pay_methods = data.data.pay_methods;
                var payMethod = payMethodPopup();
                payMethod.show({
                    payment_tips: data.data.payment_tips,
                    pay_methods: data.data.pay_methods,
                    price: data.data.discounted_price,
                    onPaymethodChange: function(value) {
                        pay_data.pay_method = value
                    },
                    onConfirm: function() {
                        goods_buy()
                    }
                });
                if (selected_pay_method) {
                    if (selected_pay_method == 8 || selected_pay_method == 9) {
                        $("#j_popup_epay .mix-item").closest(".pay-item").data("value", selected_pay_method).click();
                        $("#j_popup_epay .mix-item").show();
                        $('#j_popup_epay .mix-item[data-value="' + selected_pay_method + '"]').hide()
                    } else {
                        $('#j_popup_epay .pay-item[data-value="' + selected_pay_method + '"]').click()
                    }
                }
                get_coupons()
            }
        })
    };
    var get_coupons = function() {
        sendRequest("/api/activity/coupon/my/", {
            method: "GET",
            data: {
                state: "unuse",
                coupon_type: "reduction",
                order_amount: pay_data.price,
                sell_order_id: pay_data.sell_order_id
            },
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    return
                }
                var items = data.data.items;
                var html = template_render("coupon_info_pat", {
                    items: data.data.items
                });
                $("#j_popup_epay").find(".coupon-container").html(html);
                Buff.initSelect("#j_select_coupon");
                $('#j_select_coupon li[value="' + pay_data.cdkey_id + '"]').click();
                $("#j_select_coupon").on("change", function() {
                    if (pay_data.cdkey_id == $(this).attr("value")) {
                        return
                    }
                    pay_data.cdkey_id = $(this).attr("value");
                    buy_check($(".pay-item.on").data("value"))
                })
            }
        })
    };
    var init = function() {
        $(document).on("click", ".btn-buy-order", function(e) {
            e.preventDefault();
            $(".floattip").trigger("mouseleave");
            var sellerid = $(this).data("sellerid");
            var sell_order_id = $(this).data("orderid");
            var goods_id = $(this).data("goodsid");
            var goods = {
                icon_url: $(this).data("goods-icon-url"),
                name: $(this).data("goods-name"),
                sell_min_price: $(this).data("goods-sell-min-price")
            };
            var price = $(this).data("price");
            var mode = $(this).data("mode");
            var asset_info = $(this).data("asset-info");
            if (sellerid == current_user_id) {
                Buff.toast(i18n("cannot_purchase_your_own_items"), {
                    type: "warning"
                });
                return
            }
            pay_data = {};
            pay_data.sell_order_id = sell_order_id;
            pay_data.goods_id = goods_id;
            pay_data.price = price;
            pay_data.goods = goods;
            pay_data.cdkey_id = "";
            var get_user_info = function() {
                sendRequest("/account/api/user/info", {
                    dataType: "json",
                    method: "GET",
                    success: function(data) {
                        if (data.code != "OK") {
                            Buff.toast(data.error);
                            return
                        } else if (data.data.steamid) {
                            if (data.data.trade_url || mode == "5") {
                                check_asset_info()
                            } else {
                                Buff.alert({
                                    title: i18n("prompt"),
                                    message: i18n("you_have_yet_to_bind"),
                                    hideCancel: true,
                                    success: function() {
                                        window.open("/user-center/profile", "_blank")
                                    }
                                })
                            }
                        } else {
                            Buff.alert({
                                title: i18n("unbound_steam"),
                                message: i18n("detects_that_you_are_also"),
                                hideCancel: true,
                                confirmText: i18n("to_bind"),
                                success: function() {
                                    window.open("/user-center/profile", "_blank")
                                }
                            })
                        }
                    }
                })
            };
            var check_asset_info = function() {
                if (localStorage.getItem("remember_dismiss_check_sticker_wear")) {
                    return buy_check()
                }
                if (!asset_info || !asset_info.info || !asset_info.info.stickers) {
                    return buy_check()
                }
                var stickers = asset_info.info.stickers;
                var has_wear = false;
                for (var i = 0; i < stickers.length; i++) {
                    if (stickers[i].wear > 0) {
                        Buff.alert({
                            title: i18n("prompt"),
                            message: i18n("check_sticker_wear_in_detail"),
                            success: function() {
                                localStorage.setItem("remember_dismiss_check_sticker_wear", "1")
                            },
                            hideCancel: true,
                            confirmText: i18n("i_know")
                        });
                        has_wear = true;
                        break
                    }
                }
                if (!has_wear) {
                    buy_check()
                }
            };
            var cooldown = $(this).data("cooldown");
            if (cooldown == false) {
                get_user_info()
            } else {
                allow_tradable_cooldown = 0;
                if (mode != "2") {
                    msg = i18n("since_the_csgo_official_trading")
                } else {
                    msg = i18n("since_the_csgo_official_trading")
                }
                Buff.alert({
                    title: i18n("prompt"),
                    message: msg,
                    success: function() {
                        allow_tradable_cooldown = 1;
                        get_user_info()
                    }
                })
            }
        })
    };
    return {
        init: init,
        show_wx_pay_qrcode: show_wx_pay_qrcode,
        open_pcredit_pay: open_pcredit_pay
    }
};
var supplyBuy = function(user_id) {
    var current_user_id = user_id;
    var game = g.game;
    var supply_buy_data = {
        num: 1
    };
    var priceChangeEvent;
    var onFinishCreateBuying = function(num) {};
    var getSpecificInput = function() {
        var specific = [];
        $("#j_popup_supply .w-Select.specific-buy").each(function() {
            var value = $(this).attr("value");
            var specific_type = $(this).data("specific-type");
            if (value)
                specific.push({
                    specific_type: specific_type,
                    value: value
                })
        });
        return specific
    };
    var createSupplyBuying = function() {
        var goods_id = supply_buy_data.goods.id;
        var price = supply_buy_data.price;
        var num = supply_buy_data.num;
        var pay_method = supply_buy_data.pay_method;
        var specific = getSpecificInput();
        sendRequest("/api/market/buy_order/create", {
            data: {
                game: game,
                goods_id: goods_id,
                price: price,
                num: num,
                pay_method: pay_method,
                allow_tradable_cooldown: $("#buy-order-cooldown").attr("value") ? 1 : 0,
                specific: specific
            },
            dataType: "json",
            method: "POST",
            timeout: 1e4,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    $(".pay-btn").removeClass("i_Btn_disabled");
                    return
                }
                Buff.toast(i18n("create_buying_success"), {
                    type: "success"
                });
                Popup.hide();
                updateNavbarCashAmount();
                onFinishCreateBuying(num)
            },
            complete: function(resp) {
                if (resp.responseJSON.code == "Realname Required") {
                    $(".pay-btn").removeClass("i_Btn_disabled")
                }
            }
        })
    };
    var showBuyingPopup = function() {
        sendRequest("/api/market/goods/info", {
            data: {
                goods_id: supply_buy_data.goods_id,
                game: game
            },
            method: "GET",
            success: function(data) {
                if (!data.data.can_buy) {
                    Buff.toast(i18n("the_goods_is_not_buying"), {
                        type: "error"
                    });
                    return
                }
                supply_buy_data.specific_items = data.data.goods_info.specific;
                supply_buy_data["goods"] = data.data;
                supply_buy_data["max_num"] = MAX_NUM[data.data.appid];
                $("#j_popup_supply").remove();
                $("body").append($(template_render("supply_buy_detail_pat", supply_buy_data)));
                Popup.show("j_popup_supply")
            },
            error: function(error) {
                Buff.toast(error, {
                    type: "error"
                })
            }
        })
    };
    var showPayMethod = function() {
        sendRequest("/api/market/buy_order/create/preview", {
            data: {
                game: game,
                goods_id: supply_buy_data.goods_id,
                price: supply_buy_data.price,
                num: supply_buy_data.num,
                specific: getSpecificInput()
            },
            dataType: "json",
            method: "POST",
            timeout: 1e4,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "warning"
                    });
                    return
                }
                var show_pay_method_popup = function() {
                    supply_buy_data.pay_methods = data.data.pay_methods;
                    var payMethod = payMethodPopup();
                    payMethod.show({
                        pay_methods: supply_buy_data.pay_methods,
                        price: getTotalPrice(),
                        onPaymethodChange: function(value) {
                            supply_buy_data.pay_method = value
                        },
                        onConfirm: function() {
                            Popup.hide();
                            createSupplyBuying()
                        }
                    })
                };
                if (data.data.pay_confirm) {
                    var pay_confirm = data.data.pay_confirm;
                    Buff.alert({
                        title: pay_confirm.title,
                        message: pay_confirm.message,
                        cancelText: pay_confirm.button_cancel,
                        confirmText: pay_confirm.button_noted,
                        cancel: function() {
                            $("#j_popup_supply .supply-buy-confirm-btn").removeClass("i_Btn_disabled");
                            $("#j_popup_supply input[name=price]").focus()
                        },
                        success: function() {
                            show_pay_method_popup()
                        }
                    })
                } else {
                    show_pay_method_popup()
                }
            }
        })
    };
    var getTotalPrice = function() {
        return (supply_buy_data.price * supply_buy_data.num).toFixed(2)
    };
    var updateTotalPrice = function() {
        if (supply_buy_data.price && supply_buy_data.num) {
            var total_price = getTotalPrice();
            $("#j_popup_supply .total_amount").html(formatPriceYuan(total_price));
            $("#j_popup_supply .total_amount_custom").html(formatPriceCustom(total_price))
        }
    };
    var init = function(config) {
        var config = config || {};
        onFinishCreateBuying = config.onFinishCreateBuying || function() {}
        ;
        $(document).on("click", ".btn-supply-buy", function(e) {
            e.preventDefault();
            var goods_id = $(this).data("goodsid");
            supply_buy_data = {
                num: 1
            };
            supply_buy_data.goods_id = goods_id;
            var button = this;
            sendRequest("/account/api/user/info", {
                dataType: "json",
                method: "GET",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error);
                        return
                    } else if (data.data.steamid) {
                        if (data.data.trade_url) {
                            showBuyingPopup()
                        } else {
                            Buff.alert({
                                title: i18n("prompt"),
                                message: i18n("you_have_yet_to_bind"),
                                hideCancel: true,
                                success: function() {
                                    window.open("/user-center/profile", "_blank")
                                }
                            })
                        }
                    } else {
                        Buff.alert({
                            title: i18n("unbound_steam"),
                            message: i18n("detects_that_you_are_also"),
                            hideCancel: true,
                            confirmText: i18n("to_bind"),
                            success: function() {
                                window.open("/user-center/profile", "_blank")
                            }
                        })
                    }
                }
            })
        });
        $(document).on("change", ".w-Select.specific-buy", function() {
            var specific = getSpecificInput();
            var goods_id = $(this).data("goodsid");
            sendRequest("/api/market/buy_order/specific_preview", {
                data: {
                    game: game,
                    goods_id: goods_id,
                    specific: specific
                },
                dataType: "json",
                method: "POST",
                success: function(data) {
                    $("#j_popup_supply .iconWrapper img").attr("src", data.data.icon_url);
                    if (data.data.buy_max_price == "-") {
                        $("#j_popup_supply .buy-MaxPrice").text("-");
                        $("#j_popup_supply .buy-MaxPrice").siblings(".hide-cny").text("")
                    } else {
                        $("#j_popup_supply .buy-MaxPrice").text(formatPriceNormalYuan(data.data.buy_max_price));
                        $("#j_popup_supply .buy-MaxPrice").siblings(".hide-cny").text("(" + formatPriceNormalCustom(data.data.buy_max_price) + ")")
                    }
                    if (data.data.sell_min_price == "-") {
                        $("#j_popup_supply .sell-MinPrice").text("-");
                        $("#j_popup_supply .sell-MinPrice").siblings(".hide-cny").text("")
                    } else {
                        $("#j_popup_supply .sell-MinPrice").text(formatPriceNormalYuan(data.data.sell_min_price));
                        $("#j_popup_supply .sell-MinPrice").siblings(".hide-cny").text("(" + formatPriceNormalCustom(data.data.sell_min_price) + ")")
                    }
                    if ("buy_min_price_limit"in data.data) {
                        var cur_buy_price = $("#j_popup_supply .buyPrice").val();
                        if (cur_buy_price && parseFloat(cur_buy_price) < parseFloat(data.data.buy_min_price_limit)) {
                            $("#j_popup_supply .buyPrice").val("")
                        }
                        $("#j_popup_supply .buyPrice").attr("placeholder", i18n("buy_order_min_price", {
                            min_price: data.data.buy_min_price_limit
                        }))
                    }
                }
            })
        });
        $(document).on("input", "#j_popup_supply input[name=price]", function() {
            if (priceChangeEvent) {
                clearTimeout(priceChangeEvent)
            }
            $("#j_popup_supply").find("#purchase-price-custom").text("");
            var price = parseFloat($("#j_popup_supply input[name=price]").val());
            if (price > BuffConfig.MAX_SELL_PRICE) {
                $("#j_popup_supply input[name=price]").val(BuffConfig.MAX_SELL_PRICE).trigger("input");
                priceChangeEvent = setTimeout(function() {
                    Buff.toast(i18n("purchase_price_not_greater_than") + BuffConfig.MAX_SELL_PRICE, {
                        type: "error"
                    })
                }, 1e3);
                return
            }
            if (price < .01) {
                priceChangeEvent = setTimeout(function() {
                    Buff.toast(i18n("buy_price_cannot_be_less"), {
                        type: "error"
                    })
                }, 1e3);
                $("#j_popup_supply .supply-buy-confirm-btn").addClass("i_Btn_disabled");
                return
            }
            if (Number.isNaN(price)) {
                $("#j_popup_supply .supply-buy-confirm-btn").addClass("i_Btn_disabled");
                return
            }
            supply_buy_data.price = price;
            $("#j_popup_supply .supply-buy-confirm-btn").removeClass("i_Btn_disabled");
            updateTotalPrice();
            $("#j_popup_supply").find("#purchase-price-custom").text(formatPriceNormalCustom(price, true))
        });
        $(document).on("change", "#j_popup_supply .w-Steper", function() {
            var num = parseInt($("#j_popup_supply input[name=num]").val());
            supply_buy_data.num = num;
            updateTotalPrice()
        });
        $(document).on("click", "#j_popup_supply .supply-buy-confirm-btn", function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            showPayMethod()
        })
    };
    return {
        init: init,
        onFinishCreateBuying: onFinishCreateBuying
    }
};
var bargain = function() {
    var bargain_data = {};
    var getBargainPrice = function() {
        var bargain_price = parseFloat($("#bargain-price").val() || 0);
        $(".bargain-confirm-btn").addClass("i_Btn_disabled");
        $(".total_amount").html(formatPriceYuan(bargain_price));
        if (bargain_price > 0 && bargain_price < bargain_data.lowest_bargain_price) {
            Buff.toast(i18n("counteroffer_price_cannot_be_lower"), {
                type: "error"
            });
            return
        }
        if (bargain_price > 0 && bargain_price >= bargain_data.selling_price) {
            Buff.toast(i18n("bargain_price_must_be_lower"), {
                type: "error"
            });
            return
        }
        if (bargain_price > 0) {
            $(".bargain-confirm-btn").removeClass("i_Btn_disabled")
        }
        return bargain_price
    };
    var bind_events = function() {
        Buff.pricePatten("#bargain-price")
    };
    var show_bargain_popup = function() {
        $("#j_popup_pay").remove();
        $("#j_popup_batchbuy").remove();
        $("#j_popup_supply").remove();
        $("#j_popup_bargain").remove();
        var html = template_render("bargain_detail_pat", bargain_data);
        $("body").append(html);
        Popup.show("j_popup_bargain");
        bind_events();
        $('#pay_method li[data-selected="true"]').click()
    };
    var create_bargain = function() {
        sendRequest("/api/market/buyer_bargain/create", {
            method: "POST",
            data: {
                sell_order_id: bargain_data.sell_order_id,
                price: $("#bargain-price").val(),
                pay_method: bargain_data.pay_method
            },
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    return
                }
                Popup.hide();
                if ($(".bargain-confirm-btn").data("mode") == 5) {
                    Buff.alert({
                        title: i18n("counteroffer_request_has_been_sent"),
                        message: i18n("instrongmy_counterofferstrongattention_counteroffer_status_the"),
                        hideCancel: true
                    })
                } else {
                    Buff.toast(i18n("counteroffer_request_has_been_sent"), {
                        type: "success"
                    })
                }
            }
        })
    };
    var init = function() {
        $("body").on("click", ".bargain", function() {
            $(".floattip").trigger("mouseleave");
            var data = {
                goods: {
                    id: $(this).data("goodsid"),
                    name: $(this).data("goods-name"),
                    icon_url: $(this).data("goods-icon-url")
                },
                price: $(this).data("price"),
                lowest_bargain_price: $(this).data("lowest-bargain-price"),
                sell_order_id: $(this).data("orderid"),
                mode: $(this).data("mode"),
                selling_price: $(this).data("price"),
                asset_info: $(this).data("asset-info")
            };
            bargain_data = data;
            show_bargain_popup()
        });
        $(document).on("input", "#bargain-price", function() {
            $("#bargain-price-custom").html("");
            $("#j_popup_bargain .bargain-confirm-btn").removeClass("i_Btn_disabled");
            var price = $(this).val();
            if (price)
                $("#bargain-price-custom").html(formatPriceNormalCustom(price, true))
        });
        $(document).on("change", "#bargain-price", function() {
            getBargainPrice()
        });
        $(document).on("click", "#j_popup_bargain .bargain-confirm-btn", function() {
            if ($(this).hasClass("i_Btn_disabled"))
                return;
            $(this).addClass("i_Btn_disabled");
            var bargain_price = getBargainPrice();
            bargain_data.price = bargain_price;
            var asset_info = $(this).data("asset-info");
            var preview = function() {
                sendRequest("/api/market/buyer_bargain/create/preview", {
                    data: {
                        sell_order_id: bargain_data.sell_order_id,
                        price: bargain_data.price
                    },
                    dataType: "json",
                    method: "GET",
                    success: function(data) {
                        if (data.code != "OK") {
                            Buff.toast(data.error, {
                                type: "warning"
                            });
                            return
                        }
                        bargain_data.pay_methods = data.data.pay_methods;
                        var showPayMethods = function() {
                            var payMethod = payMethodPopup();
                            payMethod.show({
                                pay_methods: bargain_data.pay_methods,
                                price: bargain_price,
                                onPaymethodChange: function(value) {
                                    bargain_data.pay_method = value
                                },
                                onConfirm: function() {
                                    Popup.hide();
                                    create_bargain()
                                }
                            })
                        };
                        if (data.data.pay_confirm) {
                            Buff.alert({
                                title: data.data.pay_confirm.title,
                                message: data.data.pay_confirm.message,
                                confirmText: data.data.pay_confirm.button_noted,
                                cancelText: data.data.pay_confirm.button_cancel,
                                success: showPayMethods
                            })
                        } else {
                            showPayMethods()
                        }
                    }
                })
            };
            var check_asset_info = function() {
                if (localStorage.getItem("remember_dismiss_check_sticker_wear")) {
                    return preview()
                }
                var asset_info = bargain_data.asset_info;
                if (!asset_info || !asset_info.info || !asset_info.info.stickers) {
                    return preview()
                }
                var stickers = asset_info.info.stickers;
                var has_wear = false;
                for (var i = 0; i < stickers.length; i++) {
                    if (stickers[i].wear > 0) {
                        Buff.alert({
                            title: i18n("prompt"),
                            message: i18n("check_sticker_wear_in_detail"),
                            success: function() {
                                localStorage.setItem("remember_dismiss_check_sticker_wear", "1")
                            },
                            hideCancel: true,
                            confirmText: i18n("i_know")
                        });
                        has_wear = true;
                        break
                    }
                }
                if (!has_wear) {
                    preview()
                }
            };
            check_asset_info()
        })
    };
    return {
        init: init
    }
};
var payMethodPopup = function() {
    "use strict";
    var instance, onPaymethodChange = function() {}, onPayContentChange = function() {}, onConfirm = function() {}, onClose = function() {}, show = function(data) {
        var payment_tips = data.payment_tips || "";
        var pay_methods = data.pay_methods || [];
        var price = data.price || "0";
        var pay_content = data.pay_content || "";
        onPaymethodChange = data.onPaymethodChange || function() {}
        ;
        onPayContentChange = data.onPayContentChange || function() {}
        ;
        onConfirm = data.onConfirm || function() {}
        ;
        onClose = data.onClose || function() {}
        ;
        $("#j_popup_epay").remove();
        $("body").append($(template_render("pay_popup_confirm", {
            payment_tips: payment_tips,
            pay_methods: pay_methods,
            price: price,
            pay_content: pay_content
        })));
        Popup.show("j_popup_epay");
        $("#j_popup_epay .pay-item.on").click();
        onPaymethodChange($("#j_popup_epay .pay-item.on").data("value"));
        var $pay_content_item = $("#ul-container ul li.on");
        $pay_content_item.click();
        onPayContentChange($pay_content_item.data("value"), $pay_content_item.data("price-value"))
    }, calculate_price_with_pay_fee = function(price, rate) {
        if (!rate) {
            return price
        }
        var price_cent = parseFloat(price) * 100;
        var fee_cent = price_cent * parseFloat(rate) / 100;
        var price_with_fee_cent = parseInt(Math.ceil(price_cent + fee_cent));
        return price_with_fee_cent / 100
    }, init = function() {
        $(document).on("click", "#j_popup_epay .pay-item", function() {
            $("#j_popup_epay .pay-item").removeClass("on");
            $(this).addClass("on");
            var method_data = $(this).data("method");
            $("#j_popup_epay .pay-btn").text(method_data.btn_text);
            $("#j_popup_epay .pay-btn").removeClass("error-pay");
            $("#j_popup_epay .pay-btn").removeClass("i_Btn_disabled");
            if (method_data.error_entry) {
                $("#j_popup_epay .pay-btn").addClass("error-pay");
                $("#j_popup_epay .pay-btn").data("url", method_data.error_entry.url)
            } else {
                if (method_data.error) {
                    $("#j_popup_epay .pay-btn").addClass("i_Btn_disabled")
                }
                onPaymethodChange($(this).data("value"))
            }
            var pay_fee_rate = method_data.pay_fee_rate;
            var total_price = $("#ul-container ul li.on").data("price-value");
            var price_with_pay_fee = calculate_price_with_pay_fee(total_price, pay_fee_rate);
            $("#j_popup_epay .total_price").text(formatPriceNormalYuan(price_with_pay_fee));
            $("#j_popup_epay .total_price_custom").text(formatPriceNormalCustom(price_with_pay_fee))
        });
        $(document).on("click", "#ul-container ul li", function() {
            $("#ul-container ul li").removeClass("on");
            $(this).addClass("on");
            onPayContentChange($(this).data("value"), $(this).data("price-value"));
            var method_data = $("#j_popup_epay .pay-item.on").data("method");
            var pay_fee_rate = method_data.pay_fee_rate;
            var total_price = $(this).data("price-value");
            var price_with_pay_fee = calculate_price_with_pay_fee(total_price, pay_fee_rate);
            $("#j_popup_epay .total_price").text(formatPriceNormalYuan(price_with_pay_fee));
            $("#j_popup_epay .total_price_custom").text(formatPriceNormalCustom(price_with_pay_fee))
        });
        $(document).on("click", "#j_popup_epay .mix-shift", function(e) {
            e.stopPropagation();
            $("#j_popup_epay .mix-item").show();
            $(this).parent(".mix-item").hide();
            var value = $(this).parent(".mix-item").data("value");
            if ($(this).closest(".pay-item").hasClass("on"))
                onPaymethodChange(value);
            $(this).closest(".pay-item").data("value", value)
        });
        $(document).on("click", "#j_popup_epay .pay-btn", function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            if ($(this).hasClass("error-pay")) {
                window.open($(this).data("url"))
            } else {
                onConfirm()
            }
        });
        $(document).on("click", "#j_popup_epay .popup-close", function() {
            Popup.hide();
            onClose()
        })
    };
    return function() {
        if (!instance) {
            init();
            instance = {
                show: show
            }
        }
        return instance
    }
}();
var supplySell = function(user_id) {
    var current_user_id = user_id;
    var game = g.game;
    var last_url;
    var bill_order_id;
    var selected_assets = [];
    var do_supply = function(goods, buy_order, assets) {
        var manual = $("#j_popup_supply_sell_preview #jNav li.inventory").hasClass("on");
        var allow_plus = $(".inventory").hasClass("allow-plus");
        var url = "/api/market/goods/supply";
        if (manual) {
            if (allow_plus) {
                url = "/api/market/goods/supply/manual_plus"
            } else {
                url = "/api/market/goods/supply/manual"
            }
        }
        sendRequest(url, {
            data: {
                game: game,
                assets: assets,
                price: buy_order.price,
                buy_order_id: buy_order.id
            },
            dataType: "json",
            method: "POST",
            timeout: BuffConfig.STEAM_TIMEOUT + 1e3 * assets.length,
            success: function(data) {
                Popup.hide();
                if (data.code != "OK") {
                    Buff.alert({
                        title: i18n("supply_failure"),
                        message: data.error,
                        hideCancel: true,
                        success: function() {
                            window.location.reload()
                        }
                    });
                    return
                }
                if (manual) {
                    if (allow_plus) {
                        Buff.alert({
                            title: i18n("prompt"),
                            message: i18n("please_go_to_buff_the"),
                            hideCancel: true,
                            success: function() {
                                window.location.reload()
                            }
                        })
                    } else {
                        Buff.alert({
                            title: i18n("prompt"),
                            message: i18n("please_go_to_my_sell"),
                            hideCancel: true,
                            confirmText: i18n("to_shipping"),
                            success: function() {
                                window.location.href = "/market/sell_order/to_deliver?game=" + game
                            }
                        })
                    }
                } else {
                    Buff.alert({
                        title: i18n("supply_success"),
                        message: i18n("successful_supply") + assets.length + i18n("piece_of_goods"),
                        hideCancel: true,
                        success: function() {
                            window.location.reload()
                        }
                    })
                }
            }
        })
    };
    var supply_check = function(goods, buy_order) {
        $("#j_popup_supply_sell_preview").remove();
        var html = template_render("supply_sell_preview_pat", {
            goods: goods,
            buy_order: buy_order
        });
        $("body").append($(html));
        Popup.show("j_popup_supply_sell_preview");
        $("#j_popup_supply_sell_preview .packlist").showLoading();
        $("#j_popup_supply_sell_preview").find("#supply-confirm").click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            $(this).addClass("i_Btn_disabled");
            do_supply(goods, buy_order, selected_assets)
        });
        $("#j_popup_supply_sell_preview #jNav li").click(function() {
            if ($(this).hasClass("on"))
                return;
            jQuery.xhrPool.abort(last_url);
            $("#j_popup_supply_sell_preview #jNav li").removeClass("on");
            $(this).addClass("on");
            $("#j_popup_supply_sell_preview .packlist").showLoading();
            $("#j_popup_supply_sell_preview").find("#supply-confirm").addClass("i_Btn_disabled");
            $("#supply_sell_fee").html(formatPriceNormalYuan(0));
            $("#supply_sell_total_price").html(formatPriceYuan(0));
            $("#supply_sell_total_price_custom").html(formatPriceNormalCustom(0));
            $("#selected-backpack-num").text(0);
            selected_assets = [];
            supply_preview(goods, buy_order, $(this).hasClass("inventory"))
        });
        $("#j_popup_supply_sell_preview .refresh-inventory").click(function() {
            $(this).hide();
            $("#j_popup_supply_sell_preview .packlist").showLoading();
            $("#j_popup_supply_sell_preview").find("#supply-confirm").addClass("i_Btn_disabled");
            $("#supply_sell_fee").html(formatPriceNormalYuan(0));
            $("#supply_sell_total_price").html(formatPriceYuan(0));
            $("#supply_sell_total_price_custom").html(formatPriceNormalCustom(0));
            $("#selected-backpack-num").text(0);
            selected_assets = [];
            supply_preview(goods, buy_order, true, 1)
        });
        selected_assets = [];
        supply_preview(goods, buy_order, $("#j_popup_supply_sell_preview #jNav li.inventory").hasClass("on"))
    };
    var supply_preview = function(goods, buy_order, manual, force_update) {
        var preview_url = manual ? "/api/market/goods/supply/preview/manual/v2" : "/api/market/goods/supply/preview/v2";
        last_url = preview_url;
        sendRequest(preview_url, {
            data: {
                buy_order_id: buy_order.id,
                game: game,
                force_update: force_update
            },
            dataType: "json",
            showLoading: false,
            timeout: BuffConfig.STEAM_TIMEOUT,
            method: "GET",
            success: function(data) {
                var html = "";
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    html = template_render("supply_sell_preview_list_pat", {
                        error: data.error
                    })
                } else {
                    html = template_render("supply_sell_preview_list_pat", {
                        backpacks: data.data.items,
                        matched_assetids: data.data.matched_assetids,
                        goods: goods,
                        buy_order: buy_order,
                        manual: manual
                    });
                    $("#total-backpack-num").text(data.data.items.length);
                    if (manual && data.data.allow_plus) {
                        $(".inventory").addClass("allow-plus")
                    } else {
                        $(".inventory").removeClass("allow-plus")
                    }
                }
                $("#j_popup_supply_sell_preview .packlist").html(html);
                var selector = "#j_popup_supply_sell_preview .packcard li:not(.disabled), #j_popup_supply_sell_preview .card_csgo li:not(.disabled)";
                $(document).off("click", selector).on("click", selector, function() {
                    var asset = {
                        game: $(this).attr("data-game"),
                        contextid: $(this).attr("data-contextid"),
                        assetid: $(this).attr("data-assetid"),
                        classid: $(this).attr("data-classid"),
                        instanceid: $(this).attr("data-instanceid"),
                        market_hash_name: $(this).attr("data-market-hash-name")
                    };
                    if ($(this).hasClass("on")) {
                        $(this).removeClass("on");
                        var index = 0;
                        for (; index < selected_assets.length; index++) {
                            if (selected_assets[index].contextid === asset.contextid && selected_assets[index].assetid === asset.assetid && selected_assets[index].classid === asset.classid && selected_assets[index].instanceid === asset.instanceid) {
                                break
                            }
                        }
                        if (index < selected_assets.length) {
                            selected_assets.splice(index, 1)
                        }
                    } else {
                        if (selected_assets.length >= buy_order.remain_num)
                            return;
                        $(this).addClass("on");
                        selected_assets.push(asset)
                    }
                    $("#selected-backpack-num").text(selected_assets.length);
                    if (selected_assets.length > 0) {
                        $("#j_popup_supply_sell_preview").find("#supply-confirm").removeClass("i_Btn_disabled")
                    } else {
                        $("#j_popup_supply_sell_preview").find("#supply-confirm").addClass("i_Btn_disabled")
                    }
                    if (selected_assets.length >= buy_order.remain_num) {
                        $("#j_popup_supply_sell_preview").find(".packcard li,.card_csgo li").each(function() {
                            if (!$(this).hasClass("on")) {
                                $(this).find(".mask").css("display", "block")
                            } else {
                                $(this).find(".mask").hide()
                            }
                        })
                    } else {
                        $("#j_popup_supply_sell_preview").find(".mask").hide()
                    }
                    $("#supply_sell_fee").html(formatPriceNormalYuan(selected_assets.length * data.data.fee));
                    $("#supply_sell_total_price").html(formatPriceYuan(selected_assets.length * (buy_order.price - data.data.fee)));
                    $("#supply_sell_total_price_custom").html(formatPriceNormalCustom(selected_assets.length * (buy_order.price - data.data.fee)))
                });
                if (manual) {
                    $("#j_popup_supply_sell_preview").find(".refresh-inventory").show()
                } else {
                    $("#j_popup_supply_sell_preview").find(".refresh-inventory").hide()
                }
            }
        })
    };
    var init = function() {
        $(document).on("click", ".btn-supply-sell", function(e) {
            e.preventDefault();
            var buyerid = $(this).data("buyerid");
            var buy_order_id = $(this).data("orderid");
            var goods_id = $(this).data("goodsid");
            var icon_url = $(this).data("goods-icon-url");
            var goods = {
                icon_url: $(this).data("goods-icon-url"),
                name: $(this).data("goods-name"),
                sell_min_price: $(this).data("goods-sell-min-price"),
                market_hash_name: $(this).data("goods-market-hash-name"),
                rarity: $(this).data("goods-rarity"),
                can_inspect: $(this).data("can-inspect"),
                can_3d_inspect: $(this).data("can-3d-inspect")
            };
            var price = $(this).data("price");
            if (buyerid == current_user_id) {
                Buff.toast(i18n("can_not_supply_your_own"), {
                    type: "warning"
                });
                return
            }
            var buy_order = {
                id: buy_order_id,
                user_id: buyerid,
                remain_num: $(this).data("remain-num"),
                price: price,
                specific: $(this).data("specific")
            };
            supply_check(goods, buy_order)
        })
    };
    return {
        init: init
    }
};
var custom_sticker = function(is_patch) {
    var popup_callback = null;
    var add_category_tag = false;
    var search_timer = null;
    var last_query_search = null;
    var use_suggestion_hidden_id = "#custom_sticker_use_suggestion";
    var gen_param = function(category, search_name) {
        var dst_extra_param = {};
        if (category) {
            dst_extra_param["category"] = category;
            dst_extra_param["add_category_tag"] = add_category_tag
        }
        if (is_patch) {
            dst_extra_param = {
                tag_name: "patch"
            }
        }
        if (search_name) {
            dst_extra_param["search"] = search_name
        }
        return dst_extra_param
    };
    var query_order_tags = function(extra_param, page_num) {
        clearTimeout(search_timer);
        search_timer = setTimeout(function() {
            var url = "/api/market/order_tags";
            var params = {
                page_num: page_num || 1,
                game: "csgo",
                page_size: 20,
                use_suggestion: $(use_suggestion_hidden_id).val()
            };
            for (var key in extra_param) {
                params[key] = extra_param[key]
            }
            if ($(use_suggestion_hidden_id).attr("tag_ids")) {
                params["tag_ids"] = $(use_suggestion_hidden_id).attr("tag_ids")
            }
            last_query_search = extra_param["search"];
            sendRequest(url, {
                method: "GET",
                data: params,
                dataType: "json",
                showLoading: true,
                async: false,
                success: function(data) {
                    var html = "";
                    var popup_order_tags_list_id = "#popup_order_tags_list";
                    $(popup_order_tags_list_id).showLoading();
                    if (data.code == "OK") {
                        $(popup_order_tags_list_id).removeLoading();
                        html = template_render("sticks_list_pat", data.data);
                        $(popup_order_tags_list_id).html(html);
                        $("#popup_custom_sticker #popup_flower-con").scrollTop(0);
                        $("#popup_custom_patch #popup_flower-con").scrollTop(0);
                        renderPagination({
                            pager_name: "#stickers_list_pager",
                            total_count: data.data.total_count,
                            page_size: data.data.page_size,
                            page_num: page_num,
                            displayed_pages: 3,
                            onPageClick: function(page, event) {
                                event.preventDefault();
                                query_order_tags(extra_param, page)
                            }
                        })
                    } else {
                        $(popup_order_tags_list_id).removeLoading();
                        $(popup_order_tags_list_id).html(html);
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        }, 200)
    };
    var query_order_tags_by_search = function() {
        var search_name = $("#search_input").val();
        if (search_name) {
            query_order_tags(gen_param("", search_name));
            $("#popup_flower-aside-con").find("li.sticker_item").css("background", "")
        }
    };
    function _animate(prevRect, target) {
        var ms = 300;
        if (ms) {
            var currentRect = target.getBoundingClientRect();
            if (prevRect.nodeType === 1) {
                prevRect = prevRect.getBoundingClientRect()
            }
            _css(target, "transition", "none");
            _css(target, "transform", "translate3d(" + (prevRect.left - currentRect.left) + "px," + (prevRect.top - currentRect.top) + "px,0)");
            target.offsetWidth;
            _css(target, "transition", "all " + ms + "ms");
            _css(target, "transform", "translate3d(0,0,0)");
            clearTimeout(target.animated);
            target.animated = setTimeout(function() {
                _css(target, "transition", "");
                _css(target, "transform", "");
                target.animated = false
            }, ms)
        }
    }
    function _css(el, prop, val) {
        var style = el && el.style;
        if (style) {
            if (val === void 0) {
                if (document.defaultView && document.defaultView.getComputedStyle) {
                    val = document.defaultView.getComputedStyle(el, "")
                } else if (el.currentStyle) {
                    val = el.currentStyle
                }
                return prop === void 0 ? val : val[prop]
            } else {
                if (!(prop in style)) {
                    prop = "-webkit-" + prop
                }
                style[prop] = val + (typeof val === "string" ? "" : "px")
            }
        }
    }
    var init = function(callback, add_category) {
        popup_callback = callback || null;
        add_category_tag = add_category || false;
        $(document).on("click", "#custom_sticker, #custom_patch", function() {
            if ($("#search_input").val()) {
                query_order_tags_by_search()
            } else {
                $("#popup_flower-aside-con ul li.sticker_item").first().trigger("click")
            }
            Popup.show("popup_" + $(this).attr("id"));
            setTimeout(function() {
                $("#custom_sticker_search_input").append('<ul class="custom_sticker_search_input-result-list"></ul>');
                new Autocomplete("#custom_sticker_search_input",{
                    search: function(user_input) {
                        return new Promise(function(resolve, reject) {
                            var input = user_input.trim();
                            if (input.length < 1) {
                                return resolve([])
                            }
                            var url = "/api/market/sticker/suggest?";
                            var param = {
                                text: input,
                                game: g.game
                            };
                            sendRequest(url, {
                                method: "GET",
                                data: param,
                                dataType: "json",
                                showLoading: false,
                                success: function(data) {
                                    if (data.code != "OK") {
                                        Buff.toast(data.error, {
                                            type: "error"
                                        });
                                        return
                                    }
                                    if (last_query_search != input) {
                                        $(use_suggestion_hidden_id).val("0");
                                        $(use_suggestion_hidden_id).removeAttr("tag_ids")
                                    }
                                    if (!data.data || !data.data.suggestions) {
                                        return resolve([])
                                    }
                                    resolve(data.data.suggestions)
                                }
                            })
                        }
                        )
                    },
                    getResultValue: function(result) {
                        return result.option
                    },
                    onSubmit: function(result) {
                        console.log("onSubmit");
                        if (!$.isEmptyObject(result)) {
                            $(use_suggestion_hidden_id).val("1");
                            $(use_suggestion_hidden_id).attr("tag_ids", result.tag_ids)
                        }
                        $("#search_input").trigger("change");
                        console.log("onSubmit end")
                    }
                })
            }, 1e3)
        });
        $("#search_btn").click(function() {
            query_order_tags_by_search()
        });
        $(document).on("change", "#search_input", function() {
            query_order_tags_by_search()
        });
        $(document).on("click", "#popup_flower-aside-con ul li.sticker_item", function() {
            $(this).parent().find("li").css("background", "");
            $(this).css("background", "#F8F8F8");
            query_order_tags(gen_param($(this).attr("value"), ""))
        });
        $(document).on("click", ".single_sticker_row", function() {
            var sticker_row_max_count = is_patch ? 3 : 4;
            if ($("#sticker-drag").find("li > div > img").length == sticker_row_max_count) {
                return
            }
            var img_icon_url = $(this).attr("icon_url");
            var id = $(this).attr("id");
            var name = $(this).attr("name");
            var $lis = $("#sticker-drag").find("li");
            for (var i in $lis) {
                var divNode = $($lis[i]).find("div");
                if (divNode.length && !$(divNode).find("img").length) {
                    var iNode = document.createElement("i");
                    iNode.className = "icon icon_delete";
                    var $first_div = divNode[0];
                    $(iNode).insertBefore($first_div);
                    var imgNode = document.createElement("img");
                    imgNode.src = img_icon_url;
                    $(imgNode).attr("id", id);
                    $($first_div).append(imgNode);
                    $($lis[i]).attr("data-title", name);
                    break
                }
            }
        });
        var check_sticker_position = function() {
            return $("#sticker_position_checkbox").attr("value")
        };
        $(document).on("change", "#sticker_position_checkbox", function() {
            var checked = check_sticker_position();
            if (checked) {
                $("#sticker-drag").removeClass("disabled");
                $("#sticker-drag").find("li").attr("draggable", true)
            } else {
                $("#sticker-drag").addClass("disabled");
                var $lis = $("#sticker-drag").find("li");
                $lis.filter(function(index) {
                    var $el = $lis.eq(index);
                    if (!$el.find("img").length) {
                        $el.insertAfter($lis.last())
                    }
                })
            }
        });
        $("#sticker-drag").on("click", ".icon_delete", function() {
            if ($(this).parent().find("img").length) {
                var check = check_sticker_position();
                if (!check) {
                    $(this).parent().parent().append('<li class="jDrag j_tips_handler" draggable="true" data-direction="top"><div></div></li>');
                    $(this).parent().remove()
                } else {
                    $(this).parent().removeAttr("data-title");
                    $(this).parent().find("img").remove();
                    $(this).remove()
                }
            }
        });
        var draging = null;
        $("#sticker-drag").on("dragstart", "li.jDrag", function(event) {
            draging = event.currentTarget;
            $(draging).addClass("on")
        });
        $("#sticker-drag").on("dragover", "li.jDrag", function(event) {
            event.preventDefault();
            var target = event.currentTarget;
            if (target !== draging) {
                var targetRect = target.getBoundingClientRect();
                var dragingRect = draging.getBoundingClientRect();
                if (target) {
                    if (target.animated) {
                        return
                    }
                }
                var $target = $(target);
                var $draging = $(draging);
                var targetIndex = $target.index();
                var dragingIndex = $draging.index();
                if (dragingIndex < targetIndex) {
                    target.parentNode.insertBefore(draging, target.nextSibling)
                } else {
                    target.parentNode.insertBefore(draging, target)
                }
                _animate(dragingRect, draging);
                _animate(targetRect, target);
                $(draging).removeClass("on")
            }
        });
        $(document).on("click", "#popup_custom_sticker #reset, #popup_custom_patch #reset", function() {
            $("#search_input").val("");
            var checked = check_sticker_position();
            if (checked) {
                $("#sticker_position_checkbox").find("span").trigger("click")
            }
            var $lis = $("#sticker-drag").find("li");
            $lis.filter(function(index) {
                var $el = $lis.eq(index);
                if ($el.find("img").length) {
                    $el.find(".icon_delete").trigger("click")
                }
            });
            $("#popup_flower-aside-con ul li.sticker_item").first().trigger("click")
        });
        $(document).on("click", "#popup_custom_sticker #confirm, #popup_custom_patch #confirm", function() {
            var check = check_sticker_position();
            var prefix = check ? "slot_" : "";
            var img_ids = [];
            $("#sticker-drag").find("li").each(function(index, el) {
                var imgNode = $(el).find("img");
                if (imgNode.length) {
                    if (prefix) {
                        img_ids.push(prefix + index + "_" + $(imgNode[0]).attr("id"))
                    } else {
                        img_ids.push($(imgNode[0]).attr("id"))
                    }
                }
            });
            Popup.hide();
            if (popup_callback) {
                popup_callback({
                    event: "custom_sticker_confirm",
                    data: {
                        extra_tag_ids_val: img_ids.join(",")
                    }
                })
            }
        });
        $(document).on("click", "#popup_custom_sticker #cancel, #popup_custom_patch #cancel", function() {
            Popup.hide();
            if (popup_callback) {
                popup_callback({
                    event: "custom_sticker_cancel",
                    data: {
                        extra_tag_ids_val: ""
                    }
                })
            }
        })
    };
    return {
        init: init
    }
};
var market = function() {
    var game = g.game;
    var filters = [];
    var observe_data = null;
    var search_timer = null;
    var last_query_search = null;
    var render = function(name, value, title) {
        if (g.appid != 570)
            return;
        for (var i = 0; i < filters.length; i++) {
            if (filters[i].name == name) {
                filters.splice(i, 1);
                break
            }
        }
        if (typeof title != "undefined") {
            filters.push({
                name: name,
                value: value,
                title: title
            })
        }
        var start = 0;
        if (start < 0)
            start = 0;
        var show_filters = filters.slice().splice(start, filters.length);
        $(".criteria-cont .w-Key").html("");
        for (var i = 0; i < show_filters.length; i++) {
            if (show_filters[i].name == "search")
                continue;
            var span = $("<span />").text(show_filters[i].title).attr("name", show_filters[i].name);
            span.append("<i>×</i>");
            $(".criteria-cont .w-Key").append(span)
        }
    };
    var render_h1z1 = function() {
        if (g.appid != 433850)
            return;
        var value = $(".w-SelType.selected").attr("value");
        var category_group = $(".w-SelType.selected p").attr("value");
        if (value == category_group) {
            title = $(".w-SelType.selected p").text()
        } else {
            title = $('.w-SelType.selected li[value="' + value + '"]').text()
        }
        if (title) {
            var span = $("<span />").text(title);
            span.append("<i>×</i>");
            $(".criteria-cont .w-Key").html(span)
        } else {
            $(".criteria-cont .w-Key").html("")
        }
    };
    var get_tab_url = function() {
        var url = "/api/market/goods";
        var tab = "selling";
        if ($("#buying").hasClass("on")) {
            url = "/api/market/goods/buying";
            tab = "buying"
        } else if ($("#bundle").hasClass("on")) {
            url = "/api/market/goods/bundle";
            tab = "bundle"
        } else if ($("#top-bookmarked").hasClass("on")) {
            url = "/api/market/sell_order/top_bookmarked";
            tab = "top-bookmarked"
        } else if ($("#bugged-ethereal").hasClass("on")) {
            url = "/api/market/sell_order/bugged_ethereal";
            tab = "bugged-ethereal"
        }
        return {
            url: url,
            tab: tab
        }
    };
    var update_breadcrumbs = function() {
        var breadcrumbs = [];
        if ($("body").hasClass("dota2")) {
            for (var i = 0; i < filters.length; i++) {
                breadcrumbs.push(filters[i].title)
            }
        } else if ($("body").hasClass("pubg")) {
            var text = $(".w-Tag > .on > p").text();
            if (text) {
                breadcrumbs.push(text)
            }
        } else if ($("body").hasClass("h1z1") || $("body").hasClass("csgo")) {
            text = $(".w-SelType.selected > ul > li.on").text() || $(".w-SelType.selected > p").text();
            if (text) {
                breadcrumbs.push(text)
            }
        }
        return breadcrumbs
    };
    var get_query_params = function(page_num) {
        var data = {
            game: game,
            page_num: page_num
        };
        for (var i = 0; i < filters.length; i++) {
            var item = filters[i];
            data[item.name] = item.value
        }
        var category_group = $(".w-Tag[name=category_group]").attr("value");
        if (category_group) {
            data["category_group"] = category_group
        }
        var category = $(".w-SelType.selected").attr("value");
        if (category) {
            var category_group = $(".w-SelType.selected p").attr("value");
            if ($(".w-SelType.selected").attr("name")) {
                data[$(".w-SelType.selected").attr("name")] = category
            } else if (category == category_group) {
                data["category_group"] = category
            } else {
                data["category"] = category
            }
        }
        var search = $("input[name=search]").val();
        if (search && search.length > 0) {
            data["search"] = search
        }
        var price_order = $(".w-Order[name=price]").attr("value");
        if (price_order && price_order.length > 0) {
            if (price_order == "des")
                data["sort_by"] = "price.desc";
            else
                data["sort_by"] = "price.asc"
        }
        var min_price = $("input[name=min_price]").val();
        if (min_price) {
            data["min_price"] = parseFloat(min_price)
        }
        var max_price = $("input[name=max_price]").val();
        if (max_price) {
            data["max_price"] = parseFloat(max_price)
        }
        $(".w-Select,.w-Select-Multi").each(function() {
            var name = $(this).attr("name");
            var val = $(this).attr("value");
            if (typeof name != "undefined" && typeof val != "undefined" && val) {
                data[name] = val
            }
        });
        return data
    };
    var query = function(page_num, trigger) {
        clearTimeout(search_timer);
        search_timer = setTimeout(function() {
            var tab_url = get_tab_url();
            var tab = tab_url["tab"];
            var url = tab_url["url"];
            if (tab == "top-bookmarked") {
                $(".block-header .w-OrderGroup").hide()
            } else {
                $(".block-header .w-OrderGroup").show()
            }
            if (tab == "selling") {
                $("#search-extra_tag_ids").show()
            } else {
                $("#search-extra_tag_ids").hide()
            }
            page_num = page_num || 1;
            var data = get_query_params(page_num);
            if ("min_price"in data && "max_price"in data && data["min_price"] > data["max_price"]) {
                Buff.toast(i18n("minimum_price_can_not_be"), {
                    type: "warning"
                });
                return
            }
            var hash = "#tab=" + tab + "&";
            for (var name in data) {
                if (tab != "selling" && name == "extra_tag_ids") {
                    continue
                }
                if (["game"].indexOf(name) < 0)
                    hash += name + "=" + data[name] + "&"
            }
            window.location.hash = hash.slice(0, -1);
            var breadcrumbs = update_breadcrumbs();
            var breadcrumb_text = breadcrumbs.slice(0, 2).join("、") + (breadcrumbs.length > 2 ? "等" : "");
            $("span.cru-filter").text(breadcrumb_text);
            sessionStorage.setItem("breadcrumb_text", breadcrumb_text);
            sessionStorage.setItem("breadcrumb_hash", window.location.hash);
            if (breadcrumbs.length > 0) {
                $(".cru-filter").show()
            } else {
                $(".cru-filter").hide()
            }
            if (!isUserLogined() && tab == "top-bookmarked") {
                var html = '<div class="nodata"><p><i class="icon icon_nodata"></i></p><p>' + i18n("view_top_bookmarked_please_login") + '</p><a href="javascript:;" onclick="loginModule.showLogin()" class="i_Btn i_Btn_hollow">' + i18n("login") + "</a></div>";
                $("#j_market_card").html(html);
                return
            }
            if (!isUserLogined() && (data.page_num > 1 || data.page_size > 20 || data.min_price || data.max_price || data.search || data.sort_by || filters.length > 0)) {
                loginModule.showLogin();
                return
            }
            $("#j_market_card").showLoading();
            $(".pager").html("").hide();
            var params = Object.assign({}, data);
            if (params.min_price > 0) {
                params.min_price /= g.currency.rate_base_cny
            }
            if (params.max_price > 0) {
                params.max_price /= g.currency.rate_base_cny
            }
            if (tab != "selling") {
                delete params["extra_tag_ids"]
            } else {
                if ("extra_tag_ids"in params && params["extra_tag_ids"] == "custom") {
                    delete params["extra_tag_ids"]
                }
            }
            if (tab == "selling") {
                params["use_suggestion"] = $("#use_suggestion").val();
                params["trigger"] = trigger || "undefined_trigger";
                if ($("#use_suggestion").attr("goods_ids")) {
                    params["goods_ids"] = $("#use_suggestion").attr("goods_ids")
                }
                last_query_search = params["search"]
            }
            sendRequest(url, {
                method: "GET",
                data: params,
                dataType: "json",
                showLoading: false,
                success: function(data) {
                    var html = "";
                    if (data.code == "OK") {
                        data.data.isBuying = tab == "buying";
                        data.data.extra_tag_ids = params["extra_tag_ids"];
                        var template = "goods_list_pat";
                        if (tab == "bundle") {
                            template = "bundle_list_pat"
                        } else if (tab == "top-bookmarked" || tab == "bugged-ethereal") {
                            template = "sell_order_list_pat"
                        }
                        html = template_render(template, data.data)
                    }
                    $("#j_market_card").html(html);
                    $("img.lazy").lazyload();
                    if (data.code == "OK") {
                        renderPagination({
                            total_count: data.data.total_count,
                            page_size: data.data.page_size,
                            page_num: page_num,
                            onPageClick: function(page, event) {
                                event.preventDefault();
                                query(page);
                                $("html,body").scrollTop(0)
                            }
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            });
            if (tab == "bundle") {
                sendRequest("/api/market/goods/bundle/transact_history", {
                    method: "GET",
                    data: {
                        game: g.game,
                        page_size: 10
                    },
                    dataType: "json",
                    showLoading: false,
                    success: function(data) {
                        var html = "";
                        if (data.code == "OK") {
                            html = template_render("bundle_history_pat", data.data)
                        } else {
                            Buff.toast(data.error, {
                                type: "error"
                            })
                        }
                        $("#j_items_container2").html(html);
                        $("img.lazy").lazyload()
                    }
                })
            } else {
                $("#j_items_container2").html("")
            }
        }, 200)
    };
    var get_last_query_search = function() {
        return last_query_search
    };
    var init = function(data_observer) {
        $(document).on("click", ".criteria-cont .w-Key i", function() {
            var name = $(this).parent().attr("name");
            render(name, "", undefined);
            if (name == "hero") {
                $(".w-Sel-Hero li").removeClass("on");
                $(".w-Sel-Hero").attr({
                    value: ""
                })
            } else if (name == "search") {
                $("input[name=search]").val("")
            } else if (name == "custom") {
                $(".w-Tag[name=custom]").attr("value", "");
                $(".w-Tag[name=custom] span").removeClass("on")
            } else {
                $('.w-SelType[name="' + name + '"] li').removeClass("on");
                $('.w-SelType[name="' + name + '"]').attr({
                    value: ""
                })
            }
            if (g.appid == 433850) {
                $(".w-SelType.selected").attr("value", "");
                $(".w-SelType").removeClass("selected");
                $(".w-SelType li").removeClass("on");
                render_h1z1()
            }
            query()
        });
        $(document).on("change", ".w-Sel-Hero", function() {
            var name = $(this).attr("name");
            var value = $(this).attr("value");
            var title = $(this).find("li.on").attr("title");
            render(name, value, title);
            query()
        });
        $(document).on("change", ".w-SelType", function() {
            var name = $(this).attr("name");
            var value = $(this).attr("value");
            var title = $(this).find("li.on").attr("title");
            render(name, value, title);
            render_h1z1();
            query()
        });
        $(document).on("click", ".w-Counter-pannel a", function() {
            query()
        });
        $(document).on("click", "#search_btn_csgo", function() {
            query(null, "search_btn")
        });
        $(document).on("change", "input[name=search]", function() {
            var name = "search";
            var value = $(this).val();
            var title = value;
            render(name, value, title);
            query(null, "search_input")
        });
        $(document).on("change", ".market-list .w-Order", function() {
            $(this).siblings().attr("value", "");
            query()
        });
        $(document).on("change", ".w-Tag", function() {
            var value = $(this).attr("value");
            if (value) {
                render("custom", value, $(this).find(".on").text())
            } else {
                render("custom", "", undefined)
            }
            query()
        });
        $(document).on("change", ".w-Select,.w-Select-Multi", function() {
            var attr_name = $(this).attr("name");
            if (attr_name) {
                var val = $(this).attr("value");
                if (attr_name == "extra_tag_ids") {
                    if (val == "custom") {
                        return
                    }
                    if (data_observer) {
                        data_observer("last_extra_tag_ids", val)
                    }
                }
                query()
            }
        });
        var query_data = getParams(window.location.hash.substring(1));
        for (var name in query_data) {
            if (!query_data[name])
                continue;
            if (name == "min_price") {
                $("input[name=min_price]").val(query_data[name])
            } else if (name == "max_price") {
                $("input[name=max_price]").val(query_data[name])
            } else if (name == "search") {
                if (query_data[name].length > 0) {
                    $("input[name=search]").val(query_data[name]);
                    render(name, query_data[name], query_data[name])
                }
            } else if (name == "sort_by") {
                var sort_by = query_data[name].split(".");
                $(".w-Order").removeClass("w-Order_des");
                if (sort_by[1] == "desc") {
                    $(".w-Order").attr({
                        value: "des"
                    });
                    $('.w-Order[name="' + sort_by[0] + '"]').addClass("w-Order_des")
                } else if (sort_by[1] == "asc") {
                    $(".w-Order").attr({
                        value: "asc"
                    });
                    $('.w-Order[name="' + sort_by[0] + '"]').addClass("w-Order_asc")
                }
            } else if (["dota2"].indexOf(g.game) > -1 && name == "custom") {
                $(".w-Tag[name=custom]").attr("value", query_data[name]);
                $(".w-Tag[name=custom] span[value=" + query_data[name] + "]").addClass("on");
                var text = $(".w-Tag[name=custom] span[value=" + query_data[name] + "]").text();
                render(name, query_data[name], text)
            } else if (name == "extra_tag_ids") {
                $(".w-Select[name=extra_tag_ids] li").removeClass("on");
                var extra_tag_ids = query_data[name];
                $(".w-Select[name=extra_tag_ids]").attr("value", extra_tag_ids);
                var li_value = extra_tag_ids;
                if (["", "empty", "non_empty"].indexOf(extra_tag_ids) == -1) {
                    li_value = "custom"
                }
                var li_sel = $('.w-Select[name=extra_tag_ids] li[value="' + li_value + '"]');
                li_sel.addClass("on");
                $(".w-Select[name=extra_tag_ids]").attr("value", extra_tag_ids).find("h3").text(li_sel.text())
            } else if (["page_num", "sort_by"].indexOf(name) < 0) {
                if (["h1z1", "csgo"].indexOf(g.game) > -1 && ["category", "category_group"].indexOf(name) > -1) {
                    Buff.setCompValue("j_h1z1-selType", query_data[name])
                } else if (g.game == "tf2" && name == "type") {
                    Buff.setCompValue("j_h1z1-selType", query_data[name])
                } else {
                    Buff.setCompValue("search-" + name, query_data[name])
                }
                var value = $("#search-" + name).attr("value");
                var title = $("#search-" + name + " li.on").attr("title");
                render(name, value, title);
                render_h1z1()
            }
        }
        if (query_data["tab"] == "buying" || query_data["tab"] == "bundle" || query_data["tab"] == "top-bookmarked" || query_data["tab"] == "bugged-ethereal") {
            $("#selling").removeClass("on");
            $("#" + query_data["tab"]).addClass("on")
        }
        var page = query_data["page_num"] || 1;
        query(page);
        Buff.pricePatten("input[name=min_price]");
        Buff.pricePatten("input[name=max_price]");
        $(document).on("click", ".tab li", function() {
            $(".tab li").removeClass("on");
            $(this).addClass("on");
            query()
        });
        $(".w-SelType.no-click").on("click", function(e) {
            e.stopPropagation()
        })
    };
    return {
        init: init,
        get_last_query_search: get_last_query_search
    }
};
var marketShow = function(goods_id, user_id) {
    var current_user_id = user_id;
    var game = g.game;
    var _WaterFall = null;
    var scrollThreshold = 150
      , status = ""
      , _preview_page_num = 0;
    _preview_slide_page_num = 0;
    var preview_query_data = {};
    var preview_data_list = [];
    var preview_relative_goods_timer = null;
    var preview_relative_goods_xhr = null;
    var last_url = "";
    var is_jump = false;
    var last_days_value = "";
    var last_days_text = "";
    var tagFilter = null;
    var tagFilterHistory = null;
    var tagFilterBuyOrder = null;
    var tagFilterChart = null;
    var showPriceHistory = function(data) {
        var ctx = document.getElementById("myChart");
        var minLabel = undefined;
        var maxLabel = undefined;
        function format(data) {
            var labels = []
              , datasets = [];
            var cuurentLables = {}
              , cuurentY = [];
            var min = 0
              , max = 1;
            var maxTime = null;
            $.each(data, function(index, val) {
                var y = val[1]
                  , x = val[0]
                  , key = null;
                cuurentY.push(y);
                datasets.push({
                    x: moment(x).format("YYYY-MM-DD HH:mm:ss"),
                    y: y
                })
            });
            if (data.length > 0) {
                minLabel = parseInt(moment(data[0][0]).startOf("day").format("x"));
                if (minLabel < data[0][0]) {
                    minLabel += 864e5
                }
                maxLabel = parseInt(moment(data[data.length - 1][0]).startOf("day").format("x"));
                var interval = (maxLabel - minLabel) / 10;
                interval = Math.ceil(interval / 864e5) * 864e5;
                if (interval > 0) {
                    for (var l = minLabel; l <= maxLabel; l += interval) {
                        labels.push(moment(l).format("YYYY-MM-DD HH:mm:ss"))
                    }
                }
                if (labels.length == 0) {
                    minLabel = data[0][0];
                    labels.push(moment(data[0][0]).format("YYYY-MM-DD HH:mm:ss"))
                }
            }
            if (cuurentY.length) {
                min = Math.min.apply(null, cuurentY) || 0;
                max = Math.max.apply(null, cuurentY) || 1
            }
            if (data.length) {
                maxTime = moment(data[data.length - 1][0]).format("YYYY/MM/DD HH:mm:ss")
            }
            return {
                maxTime: maxTime,
                min: min,
                max: max,
                labels: labels,
                datasets: datasets
            }
        }
        var formatData = format(data.price_history);
        var min_y = formatData.min * .98;
        var max_y = formatData.max * 1.03;
        var _ticks = {
            suggestedMin: min_y,
            suggestedMax: max_y,
            beginAtZero: false,
            callback: function(value) {
                return data.currency_symbol + value
            }
        };
        if (min_y == 0) {
            _ticks.beginAtZero = true
        }
        var step = Math.round((formatData.max - formatData.min) / 7);
        if (step < 1 && max_y > 0) {
            step = max_y / 7;
            if (step < .01) {
                _ticks.stepSize = .01
            } else {
                _ticks.maxTicksLimit = 7
            }
        }
        var myChart = new Chart(ctx,{
            type: "line",
            data: {
                labels: formatData.labels,
                datasets: [{
                    data: formatData.datasets,
                    borderColor: "#7cb5ec",
                    fill: false,
                    borderWidth: 2
                }]
            },
            options: {
                borderWidth: 1,
                title: {
                    display: false,
                    text: data.price_type + "(" + data.currency + ")",
                    fontColor: "#000",
                    fontSize: "14",
                    padding: 30
                },
                tooltips: {
                    mode: "index",
                    axis: "x",
                    displayColors: false,
                    intersect: false,
                    callbacks: {
                        label: function(tooltipItem, _data) {
                            return data.price_type + data.currency_symbol + parseFloat(tooltipItem.yLabel).toFixed(2)
                        }
                    },
                    filter: function(item) {
                        if (parseInt(moment(item.xLabel).format("x")) < minLabel) {
                            return false
                        }
                        return true
                    },
                    backgroundColor: "rgba(255,255,255,0.8)",
                    titleFontColor: "#000",
                    bodyFontColor: "#000",
                    borderWidth: 1,
                    borderColor: "#7cb5ec"
                },
                layout: {
                    padding: {
                        left: 50,
                        right: 50,
                        top: 0,
                        bottom: 50
                    }
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        radius: 0,
                        hitRadius: 6
                    },
                    line: {
                        tension: 0
                    }
                },
                scales: {
                    xAxes: [{
                        type: "time",
                        bounds: "ticks",
                        distribution: "linear",
                        ticks: {
                            source: "labels"
                        },
                        time: {
                            max: formatData.maxTime,
                            unit: "day",
                            displayFormats: {
                                day: "MM-DD"
                            }
                        },
                        gridLines: {}
                    }],
                    yAxes: [{
                        ticks: _ticks
                    }]
                }
            }
        })
    };
    var get_valid_tag_ids = function() {
        var tag_ids = getParamsFromHash().tag_ids;
        if (!tag_ids)
            return tag_ids;
        var tags = tag_ids.split(",");
        var valid_tag_ids = [];
        for (var i = 0; i < tags.length; i++) {
            var tag_id = tags[i];
            if ($(".criteria:visible .w-Select-Multi h6[value=" + tag_id + "]").length > 0) {
                valid_tag_ids.push(tag_id)
            }
        }
        return valid_tag_ids.join(",") || undefined
    };
    var render_selling = function() {
        $(".new-tab li").removeClass("on");
        $(".new-tab li.selling").addClass("on");
        $("#batch-buy-btn").parent().show();
        if (tagFilter)
            tagFilter.show();
        if ($(".new-tab li.selling").hasClass("has-market-min-price")) {
            var html = template_render("market_min_price_pat");
            $(".detail-tab-cont").html(html);
            initCustomCurrency($(".detail-tab-cont"));
            return
        }
        var hashParams = getParamsFromHash();
        var page_num = hashParams.page_num || 1;
        var sort_by = hashParams.sort_by || "default";
        var mode = hashParams.mode || "";
        var allow_tradable_cooldown = hashParams.allow_tradable_cooldown || 1;
        var tag_ids = get_valid_tag_ids();
        var paintseed = hashParams.paintseed;
        var paintseed_group = hashParams.paintseed_group;
        var tier = hashParams.tier;
        var min_paintwear = hashParams.min_paintwear;
        var max_paintwear = hashParams.max_paintwear;
        var min_fade = hashParams.min_fade;
        var max_fade = hashParams.max_fade;
        var name_tag = hashParams.name_tag;
        var min_price = hashParams.min_price;
        var max_price = hashParams.max_price;
        var extra_tag_ids = hashParams.extra_tag_ids;
        if (min_price > 0 && max_price > 0 && parseFloat(min_price) > parseFloat(max_price)) {
            Buff.toast(i18n("minimum_price_can_not_be"), {
                type: "warning"
            });
            return
        }
        if (min_price > 0) {
            min_price /= g.currency.rate_base_cny
        }
        if (max_price > 0) {
            max_price /= g.currency.rate_base_cny
        }
        if (!isUserLogined() && (page_num > 1 || sort_by != "default" || tag_ids || paintseed || paintseed_group || tier || min_paintwear || max_paintwear || min_fade || max_fade || name_tag || min_price || max_price)) {
            loginModule.showLogin();
            return
        }
        $(".detail-tab-cont").showLoading();
        last_url = "/api/market/goods/sell_order";
        var data = {
            game: game,
            goods_id: goods_id,
            page_num: page_num,
            sort_by: sort_by,
            mode: mode,
            allow_tradable_cooldown: allow_tradable_cooldown,
            tag_ids: tag_ids,
            paintseed: paintseed,
            paintseed_group: paintseed_group,
            tier: tier,
            min_paintwear: min_paintwear,
            max_paintwear: max_paintwear,
            min_fade: min_fade,
            max_fade: max_fade,
            name_tag: name_tag,
            min_price: min_price,
            max_price: max_price
        };
        if (extra_tag_ids && extra_tag_ids != "custom") {
            data["extra_tag_ids"] = extra_tag_ids
        }
        sendRequest("/api/market/goods/sell_order", {
            data: data,
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error);
                    return
                }
                data.data.mode = mode;
                var html = template_render("selling_list_pat", data.data);
                $(".detail-tab-cont").html(html);
                Buff.initSelect("#mode-select");
                Buff.setCompValue("mode-select", mode || undefined);
                renderPagination({
                    total_count: data.data.total_count,
                    page_size: data.data.page_size,
                    page_num: data.data.page_num,
                    onPageClick: function(page, event) {
                        event.preventDefault();
                        updateHash("page_num", page);
                        window.scrollTo(0, 0)
                    }
                })
            },
            error: function(resp) {
                if (resp.statusText == "abort")
                    return;
                if (resp.status == 500) {
                    Buff.toast(i18n("the_system_is_busy_please"))
                } else {
                    Buff.toast(i18n("detects_network_anomalies_please_try"))
                }
                $(".detail-tab-cont").removeLoading()
            }
        })
    };
    var render_buying = function() {
        $(".new-tab li").removeClass("on");
        $(".new-tab li.buying").addClass("on");
        if (tagFilterBuyOrder)
            tagFilterBuyOrder.show();
        var hashParams = getParamsFromHash();
        var page_num = hashParams.page_num || 1;
        var tag_ids = get_valid_tag_ids();
        var tier = hashParams.tier;
        if (!isUserLogined() && (page_num > 1 || tag_ids)) {
            loginModule.showLogin();
            return
        }
        $(".detail-tab-cont").showLoading();
        last_url = "/api/market/goods/buy_order";
        sendRequest("/api/market/goods/buy_order", {
            data: {
                game: game,
                goods_id: goods_id,
                page_num: page_num,
                tag_ids: tag_ids,
                tier: tier
            },
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error);
                    return
                }
                var html = template_render("buying_list_pat", data.data);
                $(".detail-tab-cont").html(html);
                renderPagination({
                    total_count: data.data.total_count,
                    page_size: data.data.page_size,
                    page_num: data.data.page_num,
                    onPageClick: function(page, event) {
                        event.preventDefault();
                        updateHash("page_num", page);
                        window.scrollTo(0, 0)
                    }
                })
            },
            error: function(resp) {
                if (resp.statusText == "abort")
                    return;
                if (resp.status == 500) {
                    Buff.toast(i18n("the_system_is_busy_please"))
                } else {
                    Buff.toast(i18n("detects_network_anomalies_please_try"))
                }
                $(".detail-tab-cont").removeLoading()
            }
        })
    };
    var render_history = function() {
        $(".new-tab li").removeClass("on");
        $(".new-tab li.history").addClass("on");
        if (tagFilterHistory)
            tagFilterHistory.show();
        if ($(".new-tab li.history").hasClass("need-login")) {
            var html = '<div class="nodata"><p><i class="icon icon_nodata"></i></p><p>' + i18n("view_history_please_login") + '</p><a href="javascript:;" onclick="loginModule.showLogin()" class="i_Btn i_Btn_hollow">' + i18n("login") + "</a></div>";
            $(".detail-tab-cont").html(html);
            return
        }
        $(".detail-tab-cont").showLoading();
        last_url = "/api/market/goods/bill_order";
        var hashParams = getParamsFromHash();
        var tag_ids = get_valid_tag_ids();
        var paintseed = hashParams.paintseed;
        var tier = hashParams.tier;
        sendRequest("/api/market/goods/bill_order", {
            data: {
                game: game,
                goods_id: goods_id,
                tag_ids: tag_ids,
                paintseed: paintseed,
                tier: tier
            },
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error);
                    return
                }
                html = template_render("history_list_pat", data.data);
                $(".detail-tab-cont").html(html);
                renderPagination({
                    total_count: 0,
                    page_size: 0,
                    page_num: 0
                })
            },
            error: function(resp) {
                if (resp.statusText == "abort")
                    return;
                if (resp.status == 500) {
                    Buff.toast(i18n("the_system_is_busy_please"))
                } else {
                    Buff.toast(i18n("detects_network_anomalies_please_try"))
                }
                $(".detail-tab-cont").removeLoading()
            }
        })
    };
    var render_price_chart = function() {
        $(".new-tab li").removeClass("on");
        $(".new-tab li.price-chart").addClass("on");
        if (tagFilterChart) {
            if (getParamsFromHash().history == "steam") {
                tagFilterChart.hide()
            } else {
                tagFilterChart.show()
            }
        }
        if ($(".new-tab li.price-chart").hasClass("need-login")) {
            var html = '<div class="nodata"><p><i class="icon icon_nodata"></i></p><p>' + i18n("view_price_trends_please_login") + '</p><a href="javascript:;" onclick="loginModule.showLogin()" class="i_Btn i_Btn_hollow">' + i18n("login") + "</a></div>";
            $(".detail-tab-cont").html(html);
            return
        }
        $(".detail-tab-cont").showLoading();
        var url = "/api/market/goods/price_history";
        var days_url = "/api/market/goods/price_history/steam/days";
        var currency = g.currency.code;
        var days = getParamsFromHash().days || undefined;
        if (getParamsFromHash().history == "buff" || has_buff_price_history && getParamsFromHash().history != "steam") {
            url = "/api/market/goods/price_history/buff";
            days_url = "/api/market/goods/price_history/buff/days"
        }
        last_url = days_url;
        sendRequest(days_url, {
            data: {
                game: game,
                goods_id: goods_id
            },
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    return
                }
                var days_options = data.data.options;
                last_url = url;
                sendRequest(url, {
                    data: {
                        game: game,
                        goods_id: goods_id,
                        currency: currency,
                        days: days,
                        tier: getParamsFromHash().tier,
                        tag_ids: get_valid_tag_ids()
                    },
                    method: "GET",
                    dataType: "json",
                    showLoading: false,
                    success: function(data) {
                        $(".detail-tab-cont").removeLoading();
                        if (data.code != "OK") {
                            Buff.toast(data.error);
                            return
                        }
                        data.data.has_buff_price_history = has_buff_price_history;
                        data.data.days_options = days_options;
                        data.data.days = days;
                        html = template_render("price-chart", data.data);
                        $(".detail-tab-cont").html(html);
                        Buff.initSelect("#price-history-days");
                        showPriceHistory(data.data)
                    },
                    error: function(resp) {
                        if (resp.statusText == "abort")
                            return;
                        if (resp.status == 500) {
                            Buff.toast(i18n("the_system_is_busy_please"))
                        } else {
                            Buff.toast(i18n("detects_network_anomalies_please_try"))
                        }
                        $(".detail-tab-cont").removeLoading()
                    }
                })
            },
            error: function(resp) {
                if (resp.statusText == "abort")
                    return;
                if (resp.status == 500) {
                    Buff.toast(i18n("the_system_is_busy_please"))
                } else {
                    Buff.toast(i18n("detects_network_anomalies_please_try"))
                }
                $(".detail-tab-cont").removeLoading()
            }
        })
    };
    var render_related_recommendation = function() {
        $(".new-tab li").removeClass("on");
        $(".new-tab li.related").addClass("on");
        $(".detail-tab-cont").showLoading();
        last_url = "/api/market/goods/related_recommendation";
        sendRequest("/api/market/goods/related_recommendation", {
            data: {
                game: game,
                goods_id: goods_id
            },
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error);
                    return
                }
                html = template_render("related_list_pat", data.data);
                $(".detail-tab-cont").html(html);
                renderPagination({
                    total_count: data.data.total_count,
                    page_size: data.data.page_size,
                    page_num: data.data.page_num,
                    onPageClick: function(page, event) {
                        event.preventDefault();
                        updateHash("page_num", page);
                        window.scrollTo(0, 0)
                    }
                })
            },
            error: function(resp) {
                if (resp.statusText == "abort")
                    return;
                if (resp.status == 500) {
                    Buff.toast(i18n("the_system_is_busy_please"))
                } else {
                    Buff.toast(i18n("detects_network_anomalies_please_try"))
                }
                $(".detail-tab-cont").removeLoading()
            }
        })
    };
    var render_user_preview = function() {
        $(".new-tab li").removeClass("on");
        $(".new-tab li.user-preview").addClass("on");
        if ($(".new-tab li.user-preview").hasClass("need-login")) {
            var html = '<div class="nodata"><p><i class="icon icon_nodata"></i></p><p>' + i18n("view_a_player_show_please") + '</p><a href="javascript:;" onclick="loginModule.showLogin()" class="i_Btn i_Btn_hollow">' + i18n("login") + "</a></div>";
            $(".detail-tab-cont").html(html);
            return
        } else {
            html = template_render("user-preview", {});
            $(".detail-tab-cont").html(html)
        }
        Buff.initSelectMulti("#j_select-Order");
        var $jopen = $("#j-open")
          , $jpackup = $("#j-packup")
          , $jreset = $("#reset-filter")
          , $jselect = $("#j-select");
        $jopen.click(function(event) {
            $jopen.hide();
            $jpackup.show();
            $jreset.show();
            $jselect.show();
            return false
        });
        $jpackup.click(function(event) {
            $jopen.show();
            $jpackup.hide();
            $jreset.hide();
            $jselect.hide();
            return false
        });
        update_user_preview(true)
    };
    var render_paintwear_rank = function() {
        $(".new-tab li").removeClass("on");
        $(".new-tab li.paintwear-rank").addClass("on");
        if ($(".new-tab li.paintwear-rank").hasClass("need-login")) {
            var html = '<div class="nodata"><p><i class="icon icon_nodata"></i></p><p>' + i18n("view_wear_ranking_please_log") + '</p><a href="javascript:;" onclick="loginModule.showLogin()" class="i_Btn i_Btn_hollow">' + i18n("login") + "</a></div>";
            $(".detail-tab-cont").html(html);
            return
        }
        $(".rank-Type").show();
        Buff.initSelect("#rank_type-Select");
        last_url = "/api/market/paintwear_rank";
        var hashParams = getParamsFromHash();
        var page_num = hashParams.page_num || 1;
        var rank_type = hashParams.rank_type || 0;
        Buff.setCompValue("rank_type-Select", rank_type);
        $(".detail-tab-cont").showLoading();
        sendRequest("/api/market/paintwear_rank", {
            data: {
                game: game,
                goods_id: goods_id,
                page_num: page_num,
                rank_type: rank_type
            },
            method: "GET",
            dataType: "JSON",
            showLoading: false,
            success: function(data) {
                var html = '<div class="nodata"><p><i class="icon icon_nodata"></i></p><p>' + i18n("no_meet_the_requirements_of") + "</p></div>";
                $(".detail-tab-cont").removeLoading();
                if (data.code == "OK") {
                    if (data.data.ranks) {
                        html = template_render("paintwear_rank_pat", data.data);
                        $(".detail-tab-cont").html(html)
                    } else {
                        $(".detail-tab-cont").html(html);
                        return
                    }
                    $("#rank-title span").text($("#rank_type-Select").find("h3").text() || i18n("ranking_total_ranking"));
                    renderPagination({
                        total_count: data.data.total_count,
                        page_size: data.data.page_size,
                        page_num: data.data.page_num,
                        onPageClick: function(page, event) {
                            event.preventDefault();
                            updateHash("page_num", page);
                            window.scrollTo(0, 0)
                        }
                    })
                } else if (data.code == "Not Found") {
                    $(".detail-tab-cont").html(html)
                } else {
                    Buff.toast(data.error);
                    return
                }
            },
            error: function(resp) {
                if (resp.statusText == "abort")
                    return;
                if (resp.status == 500) {
                    Buff.toast(i18n("the_system_is_busy_please"))
                } else {
                    Buff.toast(i18n("detects_network_anomalies_please_try"))
                }
                $(".detail-tab-cont").removeLoading()
            }
        })
    };
    var update_user_preview = function(refresh) {
        if (status == "loading")
            return;
        status = "loading";
        var goods_ids = [];
        $(".pinterest-selects .w-Selectsearch").each(function() {
            var value = $(this).attr("value");
            if (value)
                goods_ids.push(value)
        });
        var showLoading = false;
        if (refresh) {
            $("#j_waterfull").html("");
            _WaterFall = new waterFall({
                id: "#j_waterfull",
                width: 1140,
                itemWidth: 212,
                colums: 5
            });
            _preview_page_num = 0;
            _preview_slide_page_num = 0;
            status = "";
            showLoading = true;
            preview_data_list = []
        } else {
            $("#j_waterfull-loading").showLoading()
        }
        _preview_page_num += 1;
        _preview_slide_page_num += 1;
        preview_query_data = {
            game: game,
            page_num: _preview_page_num
        };
        preview_query_data["sort_by"] = $("#j_select-Order").attr("value");
        if (goods_ids.length > 0) {
            preview_query_data.goods_ids = goods_ids.join(",")
        }
        $("#preview-total-count").text("");
        last_url = "/api/market/preview";
        sendRequest("/api/market/preview", {
            method: "GET",
            data: preview_query_data,
            showLoading: showLoading,
            success: function(data) {
                $("#j_waterfull-loading").removeLoading();
                status = "";
                if (data.code == "OK") {
                    if (data.data.items.length == 0 && data.data.page_num == 1) {
                        $(".pinterest-cont .nodata_tip").show();
                        $("#j_waterfull").css({
                            height: 0
                        });
                        $("#j_select-Order").hide()
                    } else {
                        $(".pinterest-cont .nodata_tip").hide();
                        $("#j_select-Order").show()
                    }
                    var items = data.data.items;
                    var page_size = data.data.page_size;
                    var page_num = data.data.page_num;
                    if (preview_data_list.length >= data.data.total_count || items.length == 0) {
                        status = "end";
                        return
                    } else {
                        _preview_page_num = data.data.page_num
                    }
                    var user_infos = data.data.user_infos;
                    var html = "";
                    for (var i = 0; i < data.data.items.length; i++) {
                        var item = data.data.items[i];
                        preview_data_list.push(item);
                        var temp = template_render("pinterest_item_pat", {
                            item: item,
                            user_infos: user_infos,
                            index: preview_data_list.length - 1
                        });
                        html += $.trim(temp)
                    }
                    var $els = $(html);
                    $("#j_waterfull").append($els);
                    if (_WaterFall == null) {
                        _WaterFall = new waterFall({
                            id: "#j_waterfull",
                            width: 1140,
                            itemWidth: 212,
                            colums: 5
                        })
                    }
                    _WaterFall.setPosition($els)
                } else {
                    $("#j_waterfull-loading").removeLoading();
                    Buff.toast(data.error)
                }
            }
        })
    };
    var batch_buy = function() {
        var max_amount = BuffConfig.MAX_SELL_PRICE;
        var capacity = undefined;
        var goods = undefined;
        var max_price = undefined;
        var sum_prices = [];
        var buy_num = 0;
        var total_price = 0;
        var allow_tradable_cooldown = 0;
        var pay_method;
        var sell_order_ids = [];
        var finish = function(results) {
            var success = 0
              , fail = 0;
            var fail_reasons = [];
            for (var i = 0; i < results.length; i++) {
                var result = results[i];
                if (result.success) {
                    success += 1
                } else {
                    fail += 1;
                    if (fail_reasons.indexOf(result.error) < 0) {
                        fail_reasons.push(result.error)
                    }
                }
            }
            $("#loading-cover").hide();
            Popup.hide();
            var message = "";
            if (success > 0) {
                message = i18n("a_successful_purchase") + success + i18n("piece_of_goods_please_go")
            }
            if (fail > 0) {
                if (success > 0) {
                    message += "<br>部分"
                }
                message += i18n("purchase_failure_reason_as_follows");
                for (i in fail_reasons) {
                    message += "<br>" + escapeHtml(fail_reasons[i])
                }
            }
            Buff.alert({
                title: i18n("buying_in_bulk_results"),
                message: message,
                hideCancel: true,
                success: function() {
                    window.location.reload()
                }
            })
        };
        var start_buying = function(orders) {
            if (!buy_num || !orders.length)
                return;
            Buff.alert({
                title: i18n("purchase"),
                message: i18n("please_wait"),
                hideCancel: true,
                hideConfirm: true,
                extraClasses: "batch_buying"
            });
            $("#loading-cover").show();
            var results = [];
            var buy_single_goods = function(index) {
                if (index >= buy_num || index >= orders.length) {
                    finish(results);
                    return
                }
                var order = orders[index];
                var result = undefined;
                sendRequest("/api/market/goods/buy", {
                    data: {
                        game: game,
                        goods_id: goods_id,
                        sell_order_id: order.id,
                        price: order.price,
                        batch: 1,
                        pay_method: pay_method,
                        allow_tradable_cooldown: allow_tradable_cooldown
                    },
                    dataType: "json",
                    method: "POST",
                    showLoading: false,
                    ignoreCode: ["Internal Server Error"],
                    success: function(data) {
                        if (data.code != "OK") {
                            result = {
                                success: false,
                                orderid: order.id,
                                error: data.error
                            }
                        } else {
                            result = {
                                success: true,
                                orderid: order.id,
                                data: data.data
                            }
                        }
                    },
                    error: function(resp) {
                        result = {
                            success: false,
                            orderid: order.id,
                            error: resp
                        }
                    },
                    complete: function(resp) {
                        if (resp.responseJSON.code == "Realname Required") {
                            $("#j_popup_batchbuy .i_Btn_main").removeClass("i_Btn_disabled")
                        }
                        if (!result) {
                            $("#loading-cover").hide();
                            var boxes = Popup.boxes;
                            var count = boxes.length;
                            if (count >= 2 && !boxes[count - 1].hasClass("batch_buying")) {
                                var temp = boxes[count - 1];
                                boxes[count - 1] = boxes[count - 2];
                                boxes[count - 2] = temp
                            }
                            Popup.hide();
                            return
                        }
                        results.push(result);
                        buy_single_goods(index + 1)
                    }
                })
            };
            buy_single_goods(0)
        };
        var update_orders = function(submit) {
            if (!max_price) {
                sum_prices = [];
                $("#batch-buy-total-count").parent().hide();
                update_popup_show();
                return
            }
            sendRequest("/api/market/goods/sell_order", {
                data: {
                    game: game,
                    goods_id: goods_id,
                    sort_by: "price.asc",
                    mode: "",
                    max_price: max_price,
                    page_size: capacity,
                    exclude_current_user: "1",
                    allow_tradable_cooldown: allow_tradable_cooldown
                },
                method: "GET",
                showLoading: false,
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "warning"
                        });
                        return
                    }
                    var total_count = data.data.total_count;
                    if (total_count > 1e3) {
                        total_count = "1000+"
                    }
                    if (total_count <= 1) {
                        total_count += " " + i18n("member")
                    } else {
                        total_count += " " + i18n("member") + i18n("pluar_s")
                    }
                    $("#batch-buy-total-count").text(total_count);
                    $("#batch-buy-total-count").parent().show();
                    var orders = data.data.items;
                    var _sum_prices = [];
                    var current_sum = 0;
                    sell_order_ids = [];
                    for (var i = 0; i < orders.length; i++) {
                        current_sum += parseFloat(orders[i].price);
                        sell_order_ids.push(orders[i].id);
                        _sum_prices.push(current_sum)
                    }
                    sum_prices = _sum_prices;
                    update_popup_show(submit);
                    if (submit) {
                        start_buying(orders)
                    }
                }
            })
        };
        var update_popup_show = function(submit) {
            if (!sum_prices.length) {
                total_price = 0;
                $("#j_popup_batchbuy .total_amount").html(formatPriceYuan(0));
                $("#j_popup_batchbuy .total_amount_custom").html(formatPriceCustom(0));
                $("#j_popup_batchbuy .i_Btn_main").addClass("i_Btn_disabled");
                return
            }
            if (buy_num > capacity && capacity <= sum_prices.length) {
                if (game != "csgo") {
                    Buff.toast(i18n("buff_backpack_capacity_is_insufficient"))
                } else {
                    Buff.toast(i18n("buying_in_bulk_quantity_can") + capacity + i18n("member"))
                }
                $("#batch-buy-num").val(capacity).trigger("change");
                return
            }
            if (buy_num > sum_prices.length) {
                Buff.toast(i18n("the_purchase_amount_can_not"), {
                    type: "error"
                });
                $("#batch-buy-num").val(sum_prices.length).trigger("change");
                return
            }
            total_price = sum_prices[buy_num - 1];
            $("#j_popup_batchbuy .total_amount").html(formatPriceYuan(total_price));
            $("#j_popup_batchbuy .total_amount_custom").html(formatPriceCustom(total_price));
            if (!submit) {
                $("#j_popup_batchbuy .i_Btn_main").removeClass("i_Btn_disabled")
            }
        };
        var bind_events = function() {
            $("#batch-buy-search-sell-orders").click(function() {
                update_orders(false)
            });
            $("#batch-buy-max-price").on("input", function() {
                $("#batch-buy-price-custom").text("");
                var price = $(this).val();
                if (!price)
                    return;
                $("#batch-buy-price-custom").text(formatPriceNormalCustom(price, true))
            });
            $("#batch-buy-max-price").change(function() {
                max_price = $(this).val();
                if (max_price > max_amount) {
                    $(this).val(max_amount).trigger("change")
                }
                update_orders(false)
            }).trigger("change");
            $("#batch-buy-cooldown").change(function() {
                allow_tradable_cooldown = $(this).attr("value") ? 1 : 0;
                update_orders(false)
            }).trigger("change");
            $("#batch-buy-num").on("keypress", function() {
                var code = event.keyCode || event.charCode;
                if (code >= 48 && code <= 57)
                    return true;
                return false
            });
            $("#batch-buy-num").change(function() {
                buy_num = $(this).val();
                update_popup_show()
            }).trigger("change");
            $("#j_popup_batchbuy .i_Btn_main").click(function() {
                if ($(this).hasClass("i_Btn_disabled"))
                    return;
                $(this).addClass("i_Btn_disabled");
                var that = this;
                max_price = $("#batch-buy-max-price").val();
                buy_num = $("#batch-buy-num").val();
                var order_ids = [];
                for (var i = 0; i < sell_order_ids.length && order_ids.length < buy_num; i++) {
                    order_ids.push(sell_order_ids[i])
                }
                sendRequest("/api/market/goods/batch_buy/preview", {
                    data: {
                        game: game,
                        goods_id: goods_id,
                        sell_orders: order_ids
                    },
                    dataType: "json",
                    method: "POST",
                    success: function(data) {
                        $(that).removeClass("i_Btn_disabled");
                        if (data.code != "OK") {
                            Buff.toast(data.error, {
                                type: "warning"
                            });
                            return
                        }
                        var pay_methods = data.data.pay_methods;
                        var price = data.data.price;
                        var payMethod = payMethodPopup();
                        payMethod.show({
                            pay_methods: data.data.pay_methods,
                            price: price,
                            onPaymethodChange: function(value) {
                                pay_method = value
                            },
                            onConfirm: function() {
                                Popup.hide();
                                update_orders(true)
                            }
                        })
                    }
                })
            })
        };
        var show_batch_buy_popup = function() {
            $("#j_popup_pay").remove();
            $("#j_popup_batchbuy").remove();
            $("#j_popup_supply").remove();
            $("#j_popup_bargain").remove();
            var html = template_render("batch_buy_pat", {
                goods: goods,
                capacity: capacity
            });
            $("body").append(html);
            Popup.show("j_popup_batchbuy");
            bind_events()
        };
        var get_balance = function() {
            sendRequest("/api/market/goods/batch_buy/preview", {
                data: {
                    game: game,
                    goods_id: goods_id,
                    sell_orders: []
                },
                dataType: "json",
                method: "POST",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "warning"
                        });
                        return
                    }
                    pay_methods = data.data.pay_methods;
                    show_batch_buy_popup(pay_methods)
                }
            })
        };
        var get_goods_info = function() {
            sendRequest("/api/market/goods/info", {
                data: {
                    goods_id: goods_id,
                    game: game,
                    with_sell_max_price: "1"
                },
                method: "GET",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "warning"
                        });
                        return
                    }
                    goods = data.data;
                    show_batch_buy_popup()
                }
            })
        };
        var check_backpack = function() {
            if (game == "csgo") {
                capacity = 200;
                get_goods_info();
                return
            }
            sendRequest("/api/market/backpack", {
                data: {
                    game: game
                },
                method: "GET",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "warning"
                        });
                        return
                    }
                    capacity = data.data.backpack_limit - data.data.backpack_count;
                    if (capacity <= 0) {
                        Buff.alert({
                            title: i18n("purchase_failed"),
                            message: i18n("backpack_capacity_is_insufficient_can")
                        });
                        return
                    }
                    get_goods_info()
                }
            })
        };
        check_backpack()
    };
    var getClientHeight = function() {
        return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    };
    var getScrollTop = function() {
        return window.pageYOffset || document.documentElement.scrollTop
    };
    var init_and_bind_preview = function() {
        $(document).on("change", ".pinterest-selects .w-Selectsearch", function() {
            update_user_preview(true)
        });
        $(document).on("click", "#upload_file_label", function() {
            $("#upload_file").click()
        });
        $(document).on("change", "#upload_file", function(e) {
            var files = e.target.files;
            var file = files[0];
            sendRequest("/api/feedback/gen_token", {
                method: "GET",
                showLoading: false,
                success: function(data) {
                    options = {
                        file: file,
                        upload_url: data.data.url,
                        max_file_size: data.data.max_size,
                        token: data.data.token,
                        callback: function(data) {
                            $("#upload_file_label .fileupload").html('<a href="' + data.url + '" target="_blank" onclick="event.stopPropagation();"><img src="' + data.url + '"/></a>');
                            $("#upload_file_label span").text(i18n("click_on_upload_picture"))
                        },
                        onprogress: function(e) {
                            if (e.lengthComputable) {
                                var percentVal = (e.loaded / e.total * 100).toFixed(2);
                                $("#upload_file_label span").text(i18n("is_being_uploaded") + percentVal + "%")
                            }
                        }
                    };
                    uploadFile(options)
                }
            })
        });
        $(document).on("click", "#j_popup_pubgwiki .i_Btn_main.enabled", function() {
            var that = this;
            var icon_url = $("#upload_file_label img").attr("src");
            if (!icon_url) {
                Buff.toast(i18n("please_upload_picture"));
                return
            }
            var desc = $("#j_popup_pubgwiki .input-cont input").val();
            if (desc && desc.length > 24) {
                Buff.toast(i18n("do_not_exceed_24_characters"));
                return
            }
            $(this).removeClass("enabled");
            setTimeout(function() {
                $(that).addClass("enabled")
            }, 500);
            var data = {
                icon_url: icon_url,
                desc: desc,
                appid: g.appid
            };
            var goods_ids = [];
            $("#j_popup_pubgwiki .w-Selectsearch").each(function() {
                var value = $(this).attr("value");
                if (value)
                    goods_ids.push(value)
            });
            if (goods_ids.length > 0) {
                data.goods_ids = goods_ids.join(",")
            }
            sendRequest("/api/market/preview/create", {
                method: "POST",
                showLoading: true,
                data: data,
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.toast(i18n("upload_success!_your_players_show"), {
                            type: "success"
                        });
                        setTimeout(function() {
                            window.location.reload()
                        }, 1e3)
                    } else {
                        $(that).addClass("enabled");
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        });
        $(document).on("click", "#reset-filter", function() {
            render_user_preview()
        });
        $(document).on("change", "#j_select-Order", function() {
            update_user_preview(true)
        });
        $(document).on("click", ".pinterest-action", function(e) {
            e.stopPropagation();
            if ($(this).hasClass("disabled"))
                return;
            $(this).addClass("disabled");
            var preview_id = $(this).data("previewid");
            var that = $('.pinterest-action[data-previewid="' + preview_id + '"]');
            if ($(this).hasClass("on")) {
                sendRequest("/api/market/preview/cancel/up", {
                    method: "POST",
                    data: {
                        preview_id: preview_id,
                        game: game
                    },
                    showLoading: false,
                    success: function(data) {
                        that.removeClass("disabled");
                        if (data.code == "OK") {
                            that.find("span").text(data.data.ups_num);
                            that.removeClass("on");
                            for (var i = 0; i < preview_data_list.length; i++) {
                                var item = preview_data_list[i];
                                if (item.id == preview_id) {
                                    item.up = false;
                                    item.ups_num = data.data.ups_num;
                                    break
                                }
                            }
                        } else {
                            Buff.toast(data.error, {
                                type: "error"
                            })
                        }
                    },
                    complete: function() {
                        that.removeClass("disabled")
                    }
                })
            } else {
                sendRequest("/api/market/preview/up", {
                    method: "POST",
                    data: {
                        preview_id: preview_id,
                        game: game
                    },
                    showLoading: false,
                    success: function(data) {
                        that.removeClass("disabled");
                        if (data.code == "OK") {
                            that.find("span").text(data.data.ups_num);
                            that.addClass("on");
                            for (var i = 0; i < preview_data_list.length; i++) {
                                var item = preview_data_list[i];
                                if (item.id == preview_id) {
                                    item.up = true;
                                    item.ups_num = data.data.ups_num;
                                    break
                                }
                            }
                        } else {
                            Buff.toast(data.error, {
                                type: "error"
                            })
                        }
                    },
                    complete: function() {
                        that.removeClass("disabled")
                    }
                })
            }
        });
        $(window).on("scroll", function() {
            var tabOpened = $(".new-tab li.user-preview").hasClass("on");
            if (tabOpened && _WaterFall && getClientHeight() + getScrollTop() + scrollThreshold > _WaterFall.getClientHeight()) {
                if (status === "loading" || status === "end" || status === "empty") {
                    return false
                }
                update_user_preview()
            }
        });
        $(document).on("init", ".pinterest-selects .w-Selectsearch", function() {
            if ($(this).data("init"))
                return;
            $(this).data("init", true);
            var category_group = $(this).data("categorygroup");
            new selectSearch({
                id: "#j_Selectsearch-" + category_group,
                url: "/api/market/goods/all",
                queryData: {
                    game: game,
                    category_group: category_group,
                    sort_by: "price.desc",
                    page_size: 200
                },
                setParams: function(val) {
                    return {
                        search: val
                    }
                }
            })
        });
        $(document).on("init", "#j_popup_pubgwiki .w-Selectsearch", function() {
            if ($(this).data("init"))
                return;
            $(this).data("init", true);
            var category_group = $(this).data("categorygroup");
            new selectSearch({
                id: "#j_Selectsearch_upload-" + category_group,
                url: "/api/market/goods/all",
                queryData: {
                    game: game,
                    category_group: category_group,
                    sort_by: "price.desc",
                    page_size: 200
                },
                setParams: function(val) {
                    return {
                        search: val
                    }
                }
            })
        });
        $(document).on("click", ".pinterest-img", function() {
            Popup.show("j_popup_slide");
            var index = $(this).data("index");
            var previewid = $(this).data("previewid");
            var html = '<div class="popup_slide-main swiper-container" id="j_slideBox">                    <ul class="popup_slide-pic swiper-wrapper">                    </ul>                    <a class="popup_slide-prev icon_slide_left2 swiper-button-prev" href="javascript:void(0)" ></a>                    <a class="popup_slide-next icon_slide_right2 swiper-button-next" href="javascript:void(0)"></a>                </div>';
            $("#j_slideWrapper").html(html);
            var previewid = $(this).data("previewid");
            var q1 = {
                game: game,
                direction: "larger",
                cursor: previewid,
                goods_ids: preview_query_data.goods_ids,
                sort_by: preview_query_data.sort_by
            };
            var q2 = {
                game: game,
                direction: "smaller",
                cursor: previewid,
                goods_ids: preview_query_data.goods_ids,
                sort_by: preview_query_data.sort_by
            };
            var show_relative_goods = function(previewid) {
                if (preview_relative_goods_timer) {
                    clearTimeout(preview_relative_goods_timer)
                }
                if (preview_relative_goods_xhr) {
                    preview_relative_goods_xhr.abort()
                }
                $(".popup_slide_list ul").html("");
                preview_relative_goods_timer = setTimeout(function() {
                    previewid = previewid || $("#j_slideBox .swiper-slide-active").data("previewid");
                    preview_relative_goods_xhr = sendRequest("/api/market/preview/goods", {
                        method: "GET",
                        data: {
                            preview_id: previewid,
                            game: game
                        },
                        showLoading: false,
                        showError: false,
                        success: function(data) {
                            if (data.code == "OK") {
                                var html = "";
                                for (var i = 0; i < data.data.items.length; i++) {
                                    var item = data.data.items[i];
                                    html += "<li> <span>" + formatPriceNormalCustom(item.sell_reference_price) + '</span><a href="/goods/' + item.id + '" target="_blank"><img src="' + item.goods_info.icon_url + '"/></a></li>'
                                }
                                $(".popup_slide_list ul").html(html)
                            }
                        }
                    })
                }, 500)
            };
            var swiper = new Swiper(".swiper-container",{
                navigation: {
                    nextEl: ".swiper-button-next",
                    prevEl: ".swiper-button-prev"
                },
                on: {
                    slideChange: function() {
                        var len = this.slides.length
                          , self = this;
                        show_relative_goods(null);
                        if (len - this.activeIndex <= 5) {
                            _preview_slide_page_num += 1;
                            var data = Object.assign({}, preview_query_data);
                            data.page_num = _preview_slide_page_num;
                            sendRequest("/api/market/preview", {
                                method: "GET",
                                data: data,
                                showLoading: false,
                                success: function(data) {
                                    if (data.code == "OK") {
                                        if (_preview_slide_page_num > data.data.total_page) {
                                            return
                                        }
                                        html = [];
                                        for (var i = 0; i < data.data.items.length; i++) {
                                            var item = data.data.items[i];
                                            var temp = template_render("swiper_slide_pat", {
                                                item: item
                                            });
                                            html.push(temp)
                                        }
                                        swiper.appendSlide(html)
                                    }
                                }
                            })
                        }
                    }
                }
            });
            var html = [];
            for (var i = 0; i < preview_data_list.length; i++) {
                var temp = template_render("swiper_slide_pat", {
                    item: preview_data_list[i]
                });
                html.push(temp)
            }
            swiper.appendSlide(html);
            swiper.slideTo(index, 0, false);
            show_relative_goods(previewid)
        });
        $(document).on("click", "#j-showall", function() {
            $(this).hide();
            $("#j-hideall").show();
            $("#j_popup_pubgwiki .w-Selectsearch.isextra").toggle()
        });
        $(document).on("click", "#j-hideall", function() {
            $(this).hide();
            $("#j-showall").show();
            $("#j_popup_pubgwiki .w-Selectsearch.isextra").toggle()
        })
    };
    var init = function() {
        $(".new-tab li a").click(function(e) {
            e.preventDefault();
            if ($(this).parent().hasClass("on")) {
                return
            }
            $("#batch-buy-btn").parent().hide();
            $(".rank-Type").hide();
            jQuery.xhrPool.abort(last_url);
            if ($(this).parent().hasClass("selling")) {
                updateHashData({
                    page_num: "",
                    tab: "selling"
                })
            } else if ($(this).parent().hasClass("buying")) {
                updateHashData({
                    page_num: "",
                    tab: "buying"
                })
            } else if ($(this).parent().hasClass("history")) {
                updateHashData({
                    page_num: "",
                    tab: "history"
                })
            } else if ($(this).parent().hasClass("price-chart")) {
                updateHash("tab", "price-chart")
            } else if ($(this).parent().hasClass("related")) {
                updateHash("tab", "related")
            } else if ($(this).parent().hasClass("user-preview")) {
                updateHash("tab", "user-preview")
            } else if ($(this).parent().hasClass("paintwear-rank")) {
                updateHashData({
                    page_num: 1,
                    tab: "paintwear-rank"
                })
            }
        });
        $("#not-allow-tradable-cooldown").change(function() {
            if ($(this).attr("value")) {
                updateHash("allow_tradable_cooldown", 0)
            } else {
                updateHash("allow_tradable_cooldown", 1)
            }
        });
        init_and_bind_preview();
        if (getParamsFromHash().allow_tradable_cooldown == "0") {
            $("#not-allow-tradable-cooldown").attr("value", "yes");
            $("#not-allow-tradable-cooldown span").addClass("on")
        }
        $(window).on("hashchange", function() {
            if (is_jump) {
                return
            }
            if (tagFilter)
                tagFilter.hide();
            if (tagFilterHistory)
                tagFilterHistory.hide();
            if (tagFilterBuyOrder)
                tagFilterBuyOrder.hide();
            if (tagFilterChart)
                tagFilterChart.hide();
            var tab = getParamsFromHash().tab;
            if (tab == "buying") {
                render_buying()
            } else if (tab == "history") {
                render_history()
            } else if (tab == "price-chart") {
                render_price_chart()
            } else if (tab == "related") {
                render_related_recommendation()
            } else if (tab == "user-preview") {
                render_user_preview()
            } else if (tab == "paintwear-rank") {
                render_paintwear_rank()
            } else {
                render_selling()
            }
        }).trigger("hashchange");
        $("body").on("change", "#order-by-paintwear", function() {
            if ($(this).hasClass("w-Order_asc")) {
                updateHashData({
                    page_num: 1,
                    sort_by: "paintwear.asc"
                })
            } else {
                updateHashData({
                    page_num: 1,
                    sort_by: "paintwear.desc"
                })
            }
        });
        $("body").on("change", "#order-by-price", function() {
            if ($(this).hasClass("w-Order_asc")) {
                updateHashData({
                    page_num: 1,
                    sort_by: "price.asc"
                })
            } else {
                updateHashData({
                    page_num: 1,
                    sort_by: "price.desc"
                })
            }
        });
        $("body").on("change", "#order-by-cooldown", function() {
            if ($(this).hasClass("w-Order_asc")) {
                updateHashData({
                    page_num: 1,
                    sort_by: "cooldown.asc"
                })
            } else {
                updateHashData({
                    page_num: 1,
                    sort_by: "cooldown.desc"
                })
            }
        });
        $("body").on("change", "#mode-select", function() {
            updateHashData({
                page_num: 1,
                mode: $(this).attr("value")
            })
        });
        $("body").on("change", "#history-type", function() {
            updateHash("history", $(this).attr("value"))
        });
        $("body").on("click", "#batch-buy-btn, #batch-buy-btn2", function() {
            if (g.game == "csgo" && $(this).attr("id") == "batch-buy-btn") {
                Buff.alert({
                    title: i18n("prompt"),
                    message: i18n("page_temporarily_does_not_support"),
                    hideCancel: true
                });
                return
            }
            sendRequest("/account/api/user/info", {
                dataType: "json",
                method: "GET",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error);
                        return
                    } else if (data.data.steamid) {
                        if (data.data.trade_url) {
                            batch_buy()
                        } else {
                            Buff.alert({
                                title: i18n("prompt"),
                                message: i18n("you_have_yet_to_bind"),
                                hideCancel: true,
                                success: function() {
                                    window.open("/user-center/profile", "_blank")
                                }
                            })
                        }
                    } else {
                        Buff.alert({
                            title: i18n("unbound_steam"),
                            message: i18n("detects_that_you_are_also"),
                            hideCancel: true,
                            confirmText: i18n("to_bind"),
                            success: function() {
                                window.open("/user-center/profile", "_blank")
                            }
                        })
                    }
                }
            })
        });
        $("body").on("click", ".cancel-buy-order", function() {
            var buy_order_id = $(this).data("orderid");
            var progress = $(this).data("real-num") + "/" + $(this).data("num");
            var money = formatPrice(parseFloat($(this).data("price") * ($(this).data("num") - $(this).data("real-num"))), "normal");
            Buff.alert({
                title: i18n("termination_buying"),
                message: i18n("whether_to_terminate_the_purchase", {
                    progress: progress,
                    money: money
                }),
                success: function() {
                    var doCancel = function() {
                        sendRequest("/api/market/buy_order/cancel", {
                            data: {
                                game: g.game,
                                buy_orders: [buy_order_id]
                            },
                            dataType: "json",
                            method: "POST",
                            success: function(data) {
                                if (data.code == "OK") {
                                    var result = Object.values(data.data)[0];
                                    if (result === "OK") {
                                        Buff.toast(i18n("cancel_buying_success"), {
                                            type: "success"
                                        });
                                        setTimeout(function() {
                                            window.location.reload()
                                        }, 1e3)
                                    } else {
                                        Buff.toast(result, {
                                            type: "error"
                                        })
                                    }
                                } else {
                                    Buff.toast(data.error, {
                                        type: "error"
                                    })
                                }
                            }
                        })
                    };
                    sendRequest("/api/market/buy_order/cancel/check_rate_limit", {
                        data: {
                            game: g.game,
                            buy_orders: [buy_order_id]
                        },
                        dataType: "json",
                        method: "POST",
                        success: function(data) {
                            if (data.code == "OK") {
                                doCancel()
                            } else if (data.code == "Request Rate Will Be Limited") {
                                Buff.alert({
                                    title: i18n("termination_buying"),
                                    message: data.error,
                                    success: doCancel
                                })
                            } else {
                                Buff.toast(data.error, {
                                    type: "error"
                                })
                            }
                        }
                    })
                }
            })
        });
        $("body").on("click", ".j_Goods-jump", function() {
            var goods_id = $(this).data("goodsid");
            is_jump = true;
            updateHashData({
                tag_ids: "",
                page_num: "",
                min_paintwear: "",
                max_paintwear: "",
                min_fade: "",
                max_fade: "",
                min_price: "",
                max_price: "",
                extra_tag_ids: "",
                sort_by: "",
                name_tag: ""
            });
            window.location.href = "/goods/" + goods_id + "#" + $.param(getParamsFromHash()).replace(/\+/g, "%20")
        });
        if (getParams()["from"] === "market") {
            var breadcrumb_text = sessionStorage.getItem("breadcrumb_text");
            var hash = sessionStorage.getItem("breadcrumb_hash") || "";
            if (hash && hash.substr(0, 1) != "#") {
                hash = "#" + hash
            }
            if (breadcrumb_text) {
                $("span.cru-filter").append($("<a />", {
                    href: "/market/" + game + hash,
                    text: breadcrumb_text
                }));
                $(".cru-filter").show()
            } else {
                $("span.cru-market a").attr("href", "/market/" + game + hash)
            }
        }
        $("#j_showpackage").hover(function() {
            var posTop = $(this).offset().top
              , top = posTop - 20
              , bottom = "auto";
            if (posTop + $("#j_packagebox").height() > $(window).height()) {
                top = "auto";
                bottom = 10 - $(window).scrollTop()
            }
            $("#j_packagebox").css({
                left: $(this).offset().left + $(this).width() + 10,
                top: top,
                bottom: bottom
            }).show()
        }, function() {
            boxTimer = setTimeout(function() {
                $("#j_packagebox").hide()
            }, 200)
        });
        $("#j_packagebox").hover(function() {
            if (boxTimer) {
                clearTimeout(boxTimer)
            }
        }, function() {
            $(this).hide()
        });
        $("body").on("click", ".table-toggle a", function() {
            if ($(".my-paintwear-rank.need-hide").css("display") === "none") {
                $(".my-paintwear-rank.need-hide").css("display", "table-row");
                $(this).html(i18n("click_to_collapse") + '&nbsp<div class="icon_arrow down"></div>')
            } else {
                $(".my-paintwear-rank.need-hide").css("display", "none");
                $(this).html(i18n("click_to_expand") + '&nbsp<div class="icon_arrow up"></div>')
            }
        });
        $("body").on("change", "#rank_type-Select", function() {
            var value = $(this).attr("value");
            updateHashData({
                page_num: 1,
                tab: "paintwear-rank",
                rank_type: value
            })
        });
        last_days_value = "";
        last_days_text = $("#price-history-days").find("h3").text();
        $("body").on("change", "#price-history-days", function() {
            var reset_selection = function() {
                var selector = "#price-history-days";
                if (last_days_value) {
                    $(selector + " ul li").removeClass("on");
                    $(selector).find("ul li[value=" + last_days_value + "]").addClass("on")
                }
                if (last_days_text) {
                    $(selector).find("h3").text(last_days_text)
                }
            };
            var value = $(this).attr("value");
            var $li_selected = $(this).find("li[value=" + value + "]");
            if ($li_selected && $li_selected.data("disabled")) {
                var for_premium = false;
                var msg = i18n("view_more_long_time_of");
                Buff.alert({
                    title: i18n("prompt"),
                    message: msg,
                    hideCancel: true,
                    hideConfirm: true,
                    success: function() {
                        reset_selection()
                    },
                    cancel: function() {
                        reset_selection()
                    },
                    onClose: function() {
                        reset_selection()
                    }
                });
                return
            }
            last_days_value = value;
            last_days_text = $li_selected.text();
            updateHash("days", value)
        });
        var hide_timmer = null;
        $("#j_fav").on("mouseenter", function() {
            clearTimeout(hide_timmer);
            if ($("#j_fav_list").is(":visible"))
                return;
            var target_ids = [];
            $("#j_fav_list li.add-bookmark").each(function() {
                if ($(this).data("target-type") == 5) {
                    target_ids.push($(this).data("target-id"))
                }
            });
            sendRequest("/account/api/check_bookmark/batch", {
                method: "GET",
                data: {
                    target_type: 5,
                    target_ids: target_ids.join(",")
                },
                showLoading: false,
                showError: false,
                success: function(data) {
                    if (data.code != "OK")
                        return;
                    var bmk = bookmark();
                    Object.keys(data.data.bookmarked).forEach(function(target_id) {
                        bmk.setCacheData(5, target_id, data.data.bookmarked[target_id])
                    });
                    bmk.updateView();
                    $("#j_fav_list").show()
                }
            })
        });
        $("#j_fav").on("mouseleave", function() {
            hide_timmer = setTimeout(function() {
                $("#j_fav_list").hide()
            }, 400)
        })
    };
    var setTagFilter = function(filter) {
        tagFilter = filter
    };
    var setTagFilterHistory = function(filter) {
        tagFilterHistory = filter
    };
    var setTagFilterBuyOrder = function(filter) {
        tagFilterBuyOrder = filter
    };
    var setTagFilterChart = function(filter) {
        tagFilterChart = filter
    };
    return {
        init: init,
        setTagFilter: setTagFilter,
        setTagFilterHistory: setTagFilterHistory,
        setTagFilterBuyOrder: setTagFilterBuyOrder,
        setTagFilterChart: setTagFilterChart
    }
};
var steamInventory = function() {
    var game = g.game;
    var items_data = [];
    var assets = [];
    var asset_info = {};
    var selected = {};
    var coupon_use_map = {};
    var asset_use_coupon_map = {};
    var not_use_coupon_value = "false";
    var total_count = 0;
    var _MAX_PRICE = BuffConfig.MAX_SELL_PRICE;
    var _MIN_PRICE = BuffConfig.MIN_PRICE;
    var shelve_disabled = false;
    var update_fee_timer = null;
    var get_sorted_selected = function() {
        return Object.keys(selected).sort(function(a, b) {
            return selected[a] - selected[b]
        })
    };
    var update_select_all_state = function() {
        var count = $("#j_list_card > ul > li.on").length;
        var current_page_count = $("#j_list_card > ul > li.salable").length;
        if (count < current_page_count || count === 0) {
            $(".w-Checkbox[name=select-all] span").removeClass("on");
            $(".w-Checkbox[name=select-all]").attr({
                value: ""
            })
        } else {
            $(".w-Checkbox[name=select-all] span").addClass("on");
            $(".w-Checkbox[name=select-all]").attr({
                value: "selectall"
            })
        }
    };
    var update_overpage = function(no_render) {
        var sorted_selected = get_sorted_selected();
        $("#j_overpage-handler").find(".selected-count").text(sorted_selected.length);
        $("#j_overpage-handler").find(".total-count").text(total_count);
        var total_price = 0;
        var infos = {};
        sorted_selected.forEach(function(assetid) {
            total_price += parseFloat(asset_info[assetid].steam_price);
            infos[assetid] = asset_info[assetid]
        });
        if (!no_render || sorted_selected.length == 0) {
            $("#j_overpagetip").html(template_render("overpagetip_template", {
                selected: sorted_selected,
                total_price: total_price,
                infos: infos
            }))
        } else {
            $("#j_overpagetip").find(".f_Strong").html(formatPriceNormalCustom(total_price, undefined, "USD"));
            $("#j_overpagetip").find("#selected-count").text(sorted_selected.length)
        }
    };
    var update_selected_style = function() {
        $("#j_list_card > ul > li.salable").each(function() {
            var assetid = $(this).data("assetid");
            if (selected[assetid]) {
                $(this).addClass("on")
            } else {
                $(this).removeClass("on")
            }
        })
    };
    var check_price_value = sellingPricing().check_price_value;
    var update_fee = function() {
        clearTimeout(update_fee_timer);
        jQuery.xhrPool.abort("/api/market/batch/fee");
        update_fee_timer = setTimeout(function() {
            var prices = [];
            var indices = [];
            var total_price = 0;
            var total_fee = 0;
            var coupon_ids = [];
            for (var i = 0; i < assets.length; i++) {
                if (!assets[i])
                    continue;
                if (assets[i].price > 0) {
                    if (check_price_value(assets[i].price, false) == false) {
                        return
                    }
                    if (!assets[i].has_market_min_price) {
                        prices.push(assets[i].price);
                        indices.push(i);
                        total_price += assets[i].price;
                        if (asset_use_coupon_map[assets[i].assetid] != not_use_coupon_value) {
                            coupon_ids.push(asset_use_coupon_map[assets[i].assetid])
                        } else {
                            coupon_ids.push("")
                        }
                    } else {
                        total_price += assets[i].income
                    }
                }
            }
            if (prices.length < 1) {
                $("#j_popup_selling_preview span.sale_fee").html(formatPriceYuan(total_fee));
                $("#j_popup_selling_preview span.real_income").html(formatPriceYuan(total_price - total_fee));
                $("#j_popup_selling_preview span.real_income_custom").html(formatPriceNormalCustom(total_price - total_fee));
                return
            }
            $("#j_popup_selling_preview .confirm").addClass("i_Btn_disabled");
            sendRequest("/api/market/batch/fee", {
                data: {
                    game: game,
                    prices: prices.join(","),
                    cdkey_ids: coupon_ids.join(",")
                },
                dataType: "json",
                method: "GET",
                showLoading: false,
                success: function(data) {
                    if (data.code == "OK") {
                        $("#j_popup_selling_preview .confirm").removeClass("i_Btn_disabled");
                        total_fee += parseFloat(data.data.total_fee);
                        $("#j_popup_selling_preview span.sale_fee").html(formatPriceYuan(total_fee));
                        $("#j_popup_selling_preview span.real_income").html(formatPriceYuan(total_price - parseFloat(total_fee)));
                        $("#j_popup_selling_preview span.real_income_custom").html(formatPriceNormalCustom(total_price - parseFloat(total_fee)));
                        $("#j_popup_selling_preview input[name=income]").each(function() {
                            var index = $(this).data("index") - 1;
                            if (indices.indexOf(index) != -1) {
                                if (!$(this).is(":focus")) {
                                    assets[index].income = assets[index].price - parseFloat(data.data.fees[indices.indexOf(index)]);
                                    $(this).val(assets[index].income.toFixed(2));
                                    $(this).parents("tr").find(".sell-income-custom").text(formatPriceNormalCustom(assets[index].income, true));
                                    $(this).removeClass("i_Text_error")
                                }
                            }
                        });
                        update_fee_discount_tag()
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                },
                error: function(resp) {
                    if (resp.statusText != "abort") {
                        Buff.toast("获取手续费失败，请稍后再试")
                    }
                }
            })
        }, 500)
    };
    var update_fee_discount_tag = function() {
        var asset_use_coupon = false;
        for (var assetid in asset_use_coupon_map) {
            if (asset_use_coupon_map[assetid] && asset_use_coupon_map[assetid] != not_use_coupon_value) {
                asset_use_coupon = true;
                break
            }
        }
        if (asset_use_coupon) {
            $("#discount_icon").show()
        } else {
            $("#discount_icon").hide()
        }
    };
    var hide_fee_discount_sel = function(sel_ids) {
        sel_ids.forEach(function(sel_id) {
            $("#" + sel_id).hide()
        })
    };
    var refresh_inventory = function(force, page, page_size) {
        var page = parseInt(page) || 1;
        var force = force || 0;
        var page_size = page_size || $(".w-Select[name=page_size]").attr("value") || 50;
        var query_data = {
            game: game,
            force: force,
            page_num: page,
            page_size: page_size
        };
        query_data["search"] = $(".w-Search input").val();
        var sort_by = $(".w-Order.selected").attr("name");
        var sort_value = $(".w-Order.selected").attr("value");
        if (typeof sort_by != "undefined") {
            if (sort_value == "des")
                query_data["sort_by"] = sort_by + ".desc";
            else if (sort_value == "asc")
                query_data["sort_by"] = sort_by + ".asc"
        }
        $(".w-Select").each(function() {
            var name = $(this).attr("name");
            var val = $(this).attr("value");
            if (typeof val != "undefined" && val != "0") {
                query_data[name] = val
            }
        });
        $(".w-Tag").each(function() {
            var name = $(this).attr("name");
            var val = $(this).attr("value");
            if (typeof val != "undefined" && val != "0") {
                query_data[name] = val
            }
        });
        var hero = $(".w-SelHero").attr("value");
        if (typeof hero != "undefined" && hero != "0") {
            query_data["hero"] = hero
        }
        $(".w-Select-Multi").each(function() {
            var name = $(this).attr("name");
            if (name == "rarity") {
                var val = $(this).attr("value");
                if (typeof val != "undefined" && val != "0") {
                    query_data[name] = val
                }
                return
            }
            var category = $(this).attr("value");
            if (typeof category != "undefined") {
                var category_group = $('.w-Select-Multi h6[value="' + category + '"]').attr("value");
                if (category == category_group) {
                    query_data["category_group"] = category
                } else {
                    query_data["category"] = category
                }
            }
        });
        var hash = "#";
        for (var name in query_data) {
            if (["game", "force"].indexOf(name) < 0)
                hash += name + "=" + query_data[name] + "&"
        }
        window.location.hash = hash.slice(0, -1);
        $("#refresh").html(i18n("refreshing"));
        $("#j_list_card").showLoading();
        sendRequest("/api/market/steam_inventory", {
            data: query_data,
            method: "GET",
            dataType: "json",
            showLoading: false,
            timeout: BuffConfig.STEAM_TIMEOUT,
            ignoreCode: ["Steam Binding Required", "Backpack Is Private"],
            success: function(data) {
                var html = "";
                if (data.code == "OK") {
                    total_count = data.data.total_count;
                    if ($("#j_list_card > ul > li.salable.on.punishing").length || shelve_disabled) {
                        $("#shelve").addClass("i_Btn_disabled")
                    } else {
                        $("#shelve").removeClass("i_Btn_disabled")
                    }
                    $(".brief-info").html("<span>" + i18n("quantity") + '<strong class="c_Yellow f_Normal">' + data.data.total_count + "</strong><span>" + i18n("valuation") + '<strong class="c_Yellow f_Normal">' + formatPriceNormalCustom(data.data.total_amount_usd, undefined, "USD") + "</strong></span>");
                    items_data = data.data.items;
                    if (items_data.length < 1) {
                        html = '<div class="nodata">                                    <p><i class="icon icon_nodata"></i></p>                                    <p>' + i18n("no_related") + '</p>                                    <div><a href="/market/' + game + window.location.hash + '" class="i_Btn i_Btn_hollow">' + i18n("go_to_market") + "</a></div>                                </div>"
                    } else {
                        html = template_render("item_card_pat", data.data)
                    }
                    items_data.forEach(function(item) {
                        asset_info[item.assetid] = item
                    });
                    renderPagination({
                        total_count: data.data.total_count,
                        page_size: data.data.page_size,
                        page_num: page,
                        show_size_select: false,
                        onPageClick: function(page, event) {
                            event.preventDefault();
                            refresh_inventory(0, page, data.data.page_size);
                            window.scrollTo(0, 0)
                        }
                    })
                } else if (data.code == "Backpack Is Private") {
                    html = '<div class="nodata">                                <p><i class="icon icon_unbind"></i></p>                                <p>' + data.error + '</p>                                <div><a href="https://steamcommunity.com/my/edit/settings" target="_blank" class="i_Btn i_Btn_hollow">' + i18n("go_to_set") + "</a></div>                            </div>"
                } else if (data.code == "Steam Binding Required") {
                    html = '<div class="nodata">                                <p><i class="icon icon_unbind"></i></p>                                <p>' + i18n("unbound_steam_notice") + i18n("back_for_refresh") + '</p>                                <div><a href="/user-center/profile" target="_blank" class="i_Btn i_Btn_hollow">' + i18n("go_to_bind") + "</a></div>                            </div>"
                } else {
                    Buff.toast(data.error)
                }
                $("#j_list_card").html(html);
                update_selected_style();
                update_select_all_state();
                update_overpage()
            },
            complete: function() {
                $("#refresh").html(i18n("refresh"));
                $("#j_list_card").removeLoading()
            }
        })
    };
    var check_trade_state = function() {
        sendRequest("/account/api/user/info", {
            method: "GET",
            dataType: "json",
            showLoading: false,
            timeout: 15e3,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error);
                    return
                } else if (data.data.trade_url_state != 0) {
                    $("#trade_state_tip").show();
                    $("#deposit").addClass("i_Btn_disabled");
                    $("#shelve").addClass("i_Btn_disabled");
                    shelve_disabled = true
                }
            }
        })
    };
    var init = function() {
        $(document).on("click", "#j_list_card > ul > li.salable", function() {
            $(this).toggleClass("on");
            $(this).trigger("change");
            update_select_all_state();
            update_overpage()
        });
        $(document).on("change", "#j_list_card > ul > li.salable", function() {
            var assetid = $(this).data("assetid");
            if ($(this).hasClass("on")) {
                if (Object.keys(selected).length >= 200 && !selected[assetid]) {
                    Buff.toast(i18n("up_to_200_items"));
                    $(this).toggleClass("on");
                    return
                }
                selected[assetid] = Date.now()
            } else {
                delete selected[assetid]
            }
        });
        $(document).on("click", "#refresh", function() {
            refresh_inventory(1)
        });
        $(document).on("change", ".w-Select", function() {
            refresh_inventory()
        });
        $(document).on("change", ".w-Select-Multi", function() {
            refresh_inventory()
        });
        $(document).on("change", ".w-Tag", function() {
            refresh_inventory()
        });
        $(document).on("change", ".w-SelHero", function() {
            refresh_inventory()
        });
        $(document).on("change", ".h1z1-selType", function() {
            var category = $(".w-SelType.selected").attr("value");
            if (category != "csgo_type_other") {
                refresh_inventory()
            }
        });
        $(document).on("change", ".w-Order", function() {
            $(".w-Order").removeClass("selected");
            $(this).addClass("selected");
            $(".w-Order:not(.selected)").attr({
                value: null,
                class: "w-Order"
            });
            refresh_inventory()
        });
        $(document).on("change", ".w-Search input", function() {
            refresh_inventory()
        });
        $(document).on("click", "#recheck_trade_state", function() {
            sendRequest("/api/market/steam/trade_url_state/refresh", {
                method: "POST",
                dataType: "json",
                timeout: 15e3,
                success: function(data) {
                    if (data.code == "OK") {
                        if (data.data.trade_url_state == 0) {
                            Buff.toast(i18n("your_steam_account_tradable"));
                            $("#trade_state_tip").hide();
                            $("#deposit").removeClass("i_Btn_disabled");
                            $("#shelve").removeClass("i_Btn_disabled");
                            shelve_disabled = false
                        } else if (data.data.trade_url_state == 1) {
                            Buff.toast(i18n("your_steam_account_halt"), {
                                type: "error"
                            })
                        } else if (data.data.trade_url_state == 2) {
                            Buff.toast(i18n("your_steam_acctoun_trade_limit"), {
                                type: "error"
                            })
                        }
                    } else {
                        Buff.toast(i18n("detect_fail_try_later"))
                    }
                }
            })
        });
        var hash = window.location.hash;
        var query_data = getParams(hash.substring(1));
        for (name in query_data) {
            if (!query_data[name])
                continue;
            if (name == "sort_by") {
                var f = query_data[name].split(".")[0];
                $(".w-Order").attr({
                    value: ""
                });
                $(".w-Order").removeClass("w-Order_des");
                if (query_data[name].indexOf("desc") > 0) {
                    $(".w-Order[name=" + f + "]").attr({
                        value: "des"
                    });
                    $(".w-Order[name=" + f + "]").addClass("w-Order_des")
                } else {
                    $(".w-Order[name=" + f + "]").attr({
                        value: "asc"
                    });
                    $(".w-Order[name=" + f + "]").addClass("w-Order_asc")
                }
                $(".w-Order[name=" + f + "]").addClass("selected")
            } else if (["page_num"].indexOf(name) < 0) {
                if (name == "category_group") {
                    Buff.setCompValue("search-category", query_data[name])
                } else {
                    Buff.setCompValue("search-" + name, query_data[name])
                }
            }
        }
        var page = query_data["page_num"] || 1;
        var page_size = query_data["page_size"] || 50;
        refresh_inventory(0, page, page_size);
        $(".w-Checkbox[name=select-all]").change(function() {
            var value = $(this).attr("value");
            if (value == "selectall") {
                $("#j_list_card > ul > li.salable").addClass("on");
                if ($("#j_list_card > ul > li.salable").length < 1) {
                    Buff.toast(i18n("no_available_items"))
                }
            } else {
                $("#j_list_card > ul > li.salable").removeClass("on")
            }
            $("#j_list_card > ul > li.salable").trigger("change");
            update_select_all_state();
            update_overpage()
        });
        $(".confirm-shelve").click(function(e) {
            e.preventDefault();
            var mode = $("#shelve").data("mode");
            if ($("#j_popup_sell" + mode + " .w-Checkbox").attr("value") === "dontshow") {
                localStorage.setItem("remember_dismiss_" + mode + "_sell_2", "1")
            }
            Popup.hide();
            prepareCreate()
        });
        $("#shelve").click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            var mode = $(this).data("mode");
            if (localStorage.getItem("remember_dismiss_" + mode + "_sell_2")) {
                prepareCreate();
                return
            }
            Popup.show("j_popup_sell" + mode)
        });
        var prepareCreate = function() {
            assets = [];
            var stacked = 0;
            var amount_info = undefined;
            get_sorted_selected().forEach(function(assetid) {
                var info = asset_info[assetid];
                assets.push({
                    game: info.game,
                    market_hash_name: info.market_hash_name,
                    contextid: info.contextid,
                    assetid: info.assetid,
                    classid: info.classid,
                    instanceid: info.instanceid,
                    goods_id: info.goods_id,
                    price: "",
                    income: "",
                    has_market_min_price: false
                });
                if (info.amount > 0) {
                    amount_info = info;
                    stacked += info.amount
                }
            });
            if (assets.length < 1) {
                Buff.toast(i18n("please_select_item"));
                return
            }
            var get_coupons = function(game, state, callback) {
                sendRequest("/api/activity/coupon/my/", {
                    method: "GET",
                    data: {
                        game: game,
                        state: "unuse",
                        coupon_type: "fee_discount",
                        only_coupon: 1
                    },
                    dataType: "json",
                    showLoading: false,
                    success: function(data) {
                        if (data.code != "OK") {
                            Buff.toast(data.error, {
                                type: "error"
                            });
                            return
                        }
                        var items = data.data.items;
                        if (items.length < 1) {
                            callback([], true);
                            return
                        }
                        var coupon_list = [];
                        var exist_using = false;
                        items.forEach(function(coupon) {
                            if (coupon.state != "using") {
                                coupon_list.push({
                                    label: coupon.name,
                                    value: coupon.id,
                                    desc: coupon.expire_time.message + "&nbsp" + formatTimestamp(coupon.expire_time.time, "YYYY-MM-DD")
                                });
                                exist_using = true
                            }
                        });
                        if (coupon_list.length > 0) {
                            coupon_list.push({
                                value: not_use_coupon_value,
                                label: i18n("not_use_coupon"),
                                desc: ""
                            })
                        }
                        callback(coupon_list, !exist_using && coupon_list.length < 1)
                    }
                })
            };
            var doCreate = function() {
                sendRequest("/market/sell_order/preview/" + $("#shelve").data("mode"), {
                    data: {
                        game: game,
                        assets: assets
                    },
                    dataType: "json",
                    method: "POST",
                    timeout: BuffConfig.STEAM_TIMEOUT + 1e3 * assets.length,
                    success: function(data) {
                        if (data.code == "OK") {
                            $("#popup-container").html(data.data);
                            initCustomCurrency($("#j_popup_selling_preview"));
                            Popup.show("j_popup_selling_preview");
                            Buff.pricePatten("input[name=price]");
                            Buff.pricePatten("input[name=income]");
                            get_coupons(game, "unuse", function(coupon_list, empty_coupon) {
                                coupon_use_map = {};
                                asset_use_coupon_map = {};
                                var row_sel_ids = [];
                                var sel_id_prefix = "coupon_sel_";
                                assets.forEach(function(asset_item) {
                                    row_sel_ids.push(sel_id_prefix + asset_item.assetid)
                                });
                                if (empty_coupon) {
                                    hide_fee_discount_sel(row_sel_ids);
                                    return
                                }
                                assets.forEach(function(item) {
                                    asset_use_coupon_map[item.assetid] = ""
                                });
                                coupon_list.forEach(function(coupon) {
                                    coupon_use_map[coupon.value] = true
                                });
                                var coupon_sel_callback = function(cur_sel_coupon, sel_id) {
                                    var $this = $("#" + sel_id);
                                    var pre_sel_coupon = $this.attr("data-value");
                                    coupon_use_map[pre_sel_coupon] = true;
                                    coupon_use_map[cur_sel_coupon] = false;
                                    asset_use_coupon_map[$this.attr("assetid")] = cur_sel_coupon;
                                    return new Promise(function(resolve, reject) {
                                        update_fee();
                                        resolve()
                                    }
                                    )
                                };
                                var get_coupon_select_options = function(sel_id) {
                                    var assetid = $("#" + sel_id).attr("assetid");
                                    var sel_coupon_value = asset_use_coupon_map[assetid];
                                    var add_not_use_coupon = false;
                                    var cur_index = -1;
                                    var default_index = -1;
                                    var options = [];
                                    coupon_list.forEach(function(coupon) {
                                        if (coupon_use_map[coupon.value] || sel_coupon_value == coupon.value) {
                                            if (coupon.value == not_use_coupon_value) {
                                                add_not_use_coupon = true
                                            }
                                            options.push({
                                                value: coupon.value,
                                                label: coupon.label,
                                                desc: coupon.desc
                                            });
                                            cur_index += 1;
                                            if (sel_coupon_value == coupon.value) {
                                                default_index = cur_index
                                            }
                                        }
                                    });
                                    if (!add_not_use_coupon) {
                                        options.push({
                                            value: not_use_coupon_value,
                                            label: i18n("not_use_coupon"),
                                            desc: ""
                                        })
                                    }
                                    if (options.length <= 1) {
                                        options = []
                                    }
                                    var coupon_sel_option = {
                                        placeholder: i18n("please_choose_coupon"),
                                        options: options
                                    };
                                    if (default_index != -1) {
                                        coupon_sel_option.defaultIndex = default_index
                                    }
                                    return coupon_sel_option
                                };
                                row_sel_ids.forEach(function(sel_id) {
                                    var coupon_sel_option = get_coupon_select_options(sel_id);
                                    Buff.initCouponSelect(sel_id, coupon_sel_option, coupon_sel_callback)
                                });
                                row_sel_ids.forEach(function(sel_id) {
                                    $("body").on("change", "#" + sel_id, function() {
                                        var $this_id = $(this).attr("id");
                                        row_sel_ids.forEach(function(sel_id) {
                                            if (sel_id == $this_id) {
                                                return
                                            }
                                            var coupon_sel_option = get_coupon_select_options(sel_id);
                                            Buff.initCouponSelect(sel_id, coupon_sel_option, coupon_sel_callback)
                                        })
                                    })
                                })
                            })
                        } else {
                            Buff.alert({
                                type: "error",
                                title: i18n("shelve_failed"),
                                message: data.error,
                                hideCancel: true
                            })
                        }
                    }
                })
            };
            if (stacked > assets.length) {
                Buff.alert({
                    title: i18n("listing_instructions_title"),
                    message: amount_info["name"] + i18n("listing_instructions_message"),
                    confirmText: i18n("listing_instructions_confirm"),
                    success: doCreate
                })
            } else {
                doCreate()
            }
        };
        var update_assets_price = function() {
            $("#j_popup_selling_preview tr.assets-item input[name=price]").each(function() {
                var index = $(this).data("index") - 1;
                var price = parseFloat($(this).val());
                if (isNaN(price) || $(this).val().length == 0) {
                    assets[index].price = ""
                } else {
                    assets[index].price = price
                }
            });
            $("#j_popup_selling_preview tr.assets-item input[name=income]").each(function() {
                var index = $(this).data("index") - 1;
                var income = parseFloat($(this).val());
                if (isNaN(income) || $(this).val().length == 0) {
                    assets[index].income = ""
                } else {
                    assets[index].income = income
                }
            })
        };
        $(document).on("change", ".w-Checkbox[name=combine]", function() {
            var value = $(this).attr("value");
            if (value == "combine") {
                var group_key_data = $("#j_popup_selling_preview").data("group-key");
                for (var group_key in group_key_data) {
                    if (group_key_data[group_key].assetids.length > 1) {
                        $("#j_popup_selling_preview tr.group_key_" + group_key + ":not(:first)").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + ":first .name-cont p.num").remove();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + ":first .name-cont").append('<p class="num c_Gray" style="font-size: 13px;"> ×' + group_key_data[group_key].assetids.length + "</p>");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " input").val("");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .sell-price-custom").html("");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .sell-income-custom").html("");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .pic-cont .item-count").show();
                        $("#j_popup_selling_preview tr.group_key_" + group_key).next(".des_row").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " td").css("border-bottom", "1px solid #E9E9E9");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .edit_order_desc a").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .edit_order_desc .w-Select-coupon").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .paint-wear").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .csgo_sticker_inline").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .group_key_notice").show();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " div.notes").hide()
                    }
                }
                update_assets_price();
                update_fee()
            } else {
                $("#j_popup_selling_preview tr.assets-item").show();
                $("#j_popup_selling_preview tr.assets-item .edit_order_desc a").show();
                $("#j_popup_selling_preview tr.assets-item .edit_order_desc .w-Select-coupon").show();
                $("#j_popup_selling_preview tr.assets-item .paint-wear").show();
                $("#j_popup_selling_preview tr.assets-item .csgo_sticker_inline").show();
                $("#j_popup_selling_preview tr.assets-item.has_des").next().show();
                $("#j_popup_selling_preview tr.assets-item.has_des td").css("border-bottom", "0");
                $("#j_popup_selling_preview tr.assets-item .name-cont p.num").remove();
                $("#j_popup_selling_preview tr.assets-item .pic-cont .item-count").hide();
                $("#j_popup_selling_preview tr.assets-item .group_key_notice").hide();
                $("#j_popup_selling_preview tr.assets-item div.notes").show()
            }
        });
        $(document).on("input", "#j_popup_selling_preview input[name=price]", function() {
            var index = $(this).data("index") - 1;
            var input_price = $(this).val();
            var input_income = $(this).parents("tr").find("input[name=income]").val();
            var price = parseFloat(input_price);
            var income = parseFloat(input_income);
            var market_min_price = parseFloat($(this).data("market-min-price"));
            if (market_min_price > 0 && price < market_min_price) {
                price = market_min_price
            }
            if (check_price_value($(this).val())) {
                $(this).removeClass("i_Text_error")
            } else {
                $(this).addClass("i_Text_error")
            }
            assets[index].price = price;
            assets[index].income = income;
            assets[index].has_market_min_price = market_min_price > 0;
            var value = $(".w-Checkbox[name=combine]").attr("value");
            if (value == "combine") {
                var group_key_data = $("#j_popup_selling_preview").data("group-key");
                var group_key = $(this).data("group-key");
                var assetids = group_key_data[group_key].assetids;
                for (var i = 0; i < assets.length; i++) {
                    if (assetids.indexOf(assets[i].assetid) > -1) {
                        assets[i].price = assets[index].price;
                        assets[i].income = assets[index].income;
                        assets[i].has_market_min_price = assets[index].has_market_min_price
                    }
                }
                $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=price]").val(input_price);
                $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=income]").val(input_income);
                $("#j_popup_selling_preview tr.group_key_" + group_key + " .sell-price-custom").html(price ? formatPriceNormalCustom(price, true) : "");
                $("#j_popup_selling_preview tr.group_key_" + group_key + " .sell-price-income").html(income ? formatPriceNormalCustom(income, true) : "");
                if ($(this).hasClass("i_Text_error")) {
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=price]").addClass("i_Text_error");
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=income]").addClass("i_Text_error")
                } else {
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=price]").removeClass("i_Text_error");
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=income]").removeClass("i_Text_error");
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " .cannot-quick-pricing").remove()
                }
            }
            if (price) {
                $(this).parents("tr").find(".sell-price-custom").html(formatPriceNormalCustom(price, true))
            } else {
                $(this).parents("tr").find(".sell-price-custom").html("")
            }
            update_fee()
        });
        $(document).on("change", "#j_popup_selling_preview input[name=price]", function() {
            if (check_price_value($(this).val(), true)) {
                update_fee()
            }
        });
        var selling_pricing = sellingPricing();
        $(document).on("input", "#j_popup_selling_preview input[name=income]", function() {
            var row = $(this).parents("tr");
            var asset_id = $(row).attr("id").replace("asset_", "");
            var coupon_id = asset_use_coupon_map[asset_id] != "false" ? asset_use_coupon_map[asset_id] : "";
            selling_pricing.get_price_from_income(row, coupon_id);
            var income = $(this).val();
            if (income) {
                $(this).parents("tr").find(".sell-income-custom").html(formatPriceNormalCustom(income, true))
            } else {
                $(this).parents("tr").find(".sell-income-custom").html("")
            }
        });
        $(document).on("change", "#j_popup_selling_preview input[name=income]", function() {
            if (check_price_value($(this).val(), true)) {
                var row = $(this).parents("tr");
                var asset_id = $(row).attr("id").replace("asset_", "");
                var coupon_id = asset_use_coupon_map[asset_id] != "false" ? asset_use_coupon_map[asset_id] : "";
                selling_pricing.get_price_from_income(row, coupon_id)
            }
        });
        $(document).on("click", "#j_popup_selling_preview #quick-pricing", function() {
            selling_pricing.quick_pricing($("#j_popup_selling_preview"));
            update_fee()
        });
        $(document).on("click", "#j_popup_selling_preview .confirm:not(.i_Btn_disabled)", function() {
            for (var i = 0; i < assets.length; i++) {
                if (check_price_value(assets[i].price, true) == false) {
                    return
                }
            }
            var confirmSelling = function() {
                var assets_with_coupon = [];
                assets.forEach(function(item) {
                    var cdkey_id = asset_use_coupon_map[item.assetid] || "";
                    if (cdkey_id != not_use_coupon_value) {
                        item["cdkey_id"] = cdkey_id
                    }
                    assets_with_coupon.push(item)
                });
                sendRequest("/api/market/sell_order/create/" + $("#shelve").data("mode"), {
                    data: {
                        game: game,
                        assets: assets
                    },
                    method: "POST",
                    timeout: BuffConfig.STEAM_TIMEOUT + 1e3 * assets.length,
                    success: function(data) {
                        if (data.code == "OK") {
                            var msg = "";
                            var success = 0;
                            var failures = [];
                            for (var i = 0; i < assets.length; i++) {
                                var assetid = assets[i].assetid;
                                var result = data.data[assetid];
                                if (result == "OK") {
                                    success += 1;
                                    delete selected[assetid]
                                } else {
                                    failures.push({
                                        asset: assets[i],
                                        reason: result,
                                        info: asset_info[assetid]
                                    })
                                }
                            }
                            if (failures.length > 0) {
                                Popup.hide();
                                var html = template_render("result_pat", {
                                    failures: failures,
                                    success: success
                                });
                                $("#popup-container").html(html);
                                Popup.show("j_popup_charge-result")
                            } else {
                                if ($(".c_Yellow.offline_tips").is(":visible")) {
                                    Popup.hide();
                                    Buff.alert({
                                        title: i18n("shelve_success"),
                                        message: i18n("shelve_notice"),
                                        rememberDismiss: "deliver_tips",
                                        hideCancel: true,
                                        success: function(dismiss) {
                                            if (dismiss) {
                                                Buff.toast(i18n("shelve_success"), {
                                                    type: "success"
                                                });
                                                Popup.hide()
                                            }
                                        }
                                    })
                                } else {
                                    Buff.toast(i18n("shelve_success"), {
                                        type: "success"
                                    });
                                    Popup.hide()
                                }
                            }
                            refresh_inventory(0, $(".pager li.active .current").html())
                        } else if (data.code == "Invalid Argument" && data.error.indexOf("price") > -1) {
                            Buff.toast(i18n("unset_price_item"), {
                                type: "error"
                            })
                        } else {
                            Buff.toast(data.error || data.code, {
                                type: "warning"
                            })
                        }
                    }
                })
            };
            selling_pricing.find_unusual_price($("#j_popup_selling_preview"), function() {
                var has_sticker = false;
                for (var i = 0; i < assets.length; i++) {
                    var stickers = asset_info[assets[i].assetid].asset_info.info.stickers;
                    if (stickers && stickers.length > 0) {
                        for (var j = 0; j < stickers.length; j++) {
                            if (stickers[j].category != "patch") {
                                has_sticker = true;
                                break
                            }
                        }
                    }
                    if (has_sticker)
                        break
                }
                if (has_sticker) {
                    Buff.alert({
                        title: i18n("prompt"),
                        message: i18n("scratch_sticker_notice"),
                        cancelText: i18n("reconfirm"),
                        confirmText: i18n("continue_selling"),
                        rememberDismiss: "scratch_sticker_notice",
                        success: confirmSelling
                    })
                } else {
                    confirmSelling()
                }
            })
        });
        $("#deposit").click(function() {
            if ($(this).hasClass("i_Btn_disabled"))
                return;
            var promptRule = function() {
                Buff.alert({
                    title: i18n("prompt"),
                    message: i18n("fraud_notice"),
                    cancelText: i18n("go_to_check"),
                    confirmText: i18n("i_know"),
                    rememberDismiss: "fraud_notice",
                    hide_popup_after_cancel: false,
                    success: prepareDeposit,
                    cancel: function() {
                        openPageOnNewTab("https://steamcommunity.com/dev/apikey")
                    }
                })
            };
            if (game == "csgo") {
                Buff.alert({
                    title: i18n("deposit_backpack"),
                    message: i18n("csgo_deposit_notice"),
                    rememberDismiss: "csgo_deposit",
                    success: promptRule
                })
            } else {
                promptRule()
            }
        });
        var prepareDeposit = function() {
            assets = [];
            var stacked = 0;
            var amount_info = undefined;
            get_sorted_selected().forEach(function(assetid) {
                var info = asset_info[assetid];
                assets.push({
                    game: info.game,
                    market_hash_name: info.market_hash_name,
                    contextid: info.contextid,
                    assetid: info.assetid,
                    classid: info.classid,
                    instanceid: info.instanceid
                });
                if (info.amount > 0) {
                    amount_info = info;
                    stacked += info.amount
                }
            });
            if (assets.length < 1) {
                Buff.toast(i18n("please_select_deposit_item"));
                return
            }
            var doDeposit = function() {
                sendRequest("/api/market/backpack/deposit", {
                    data: {
                        game: game,
                        assets: assets
                    },
                    dataType: "json",
                    method: "POST",
                    success: function(data) {
                        if (data.code == "OK") {
                            bot_trades = {};
                            bot_trades[data.data.id] = data.data;
                            update_bot();
                            selected = {};
                            refresh_inventory()
                        } else if (data.code == "Steam Trade URL Failure") {
                            Buff.alert({
                                title: i18n("prompt"),
                                message: i18n("your_steam_trade_url_invalid"),
                                success: function() {
                                    window.open("/user-center/profile", "_blank")
                                },
                                cancel: function() {
                                    Buff.toast(i18n("deposit_failed"))
                                }
                            })
                        } else {
                            Buff.alert({
                                type: "error",
                                title: i18n("deposit_failed"),
                                message: data.error,
                                hideCancel: true
                            })
                        }
                    }
                })
            };
            if (stacked > assets.length) {
                Buff.alert({
                    title: i18n("deposit_instructions_title"),
                    message: amount_info["name"] + i18n("deposit_instructions_message"),
                    confirmText: i18n("deposit_instructions_confirm"),
                    success: doDeposit
                })
            } else {
                doDeposit()
            }
        };
        $(document).on("click", ".edit_order_desc a", function() {
            var assetid = $(this).data("assetid");
            Popup.show("j_pupup_add_desc");
            var content = $("#asset_" + assetid).next().find(".desc_content").text();
            $("#j_pupup_add_desc .addDesCount").text(content.length + "/40");
            $("#j_pupup_add_desc .addDesWrapper textarea").val(content);
            $("#j_pupup_add_desc .i_Btn_main").data("assetid", assetid)
        });
        $(document).on("click", "#j_pupup_add_desc .i_Btn_main", function() {
            var assetid = $(this).data("assetid");
            var content = $("#j_pupup_add_desc .addDesWrapper textarea").val();
            if (content.length > 40) {
                Buff.toast(i18n("input_content_too_long_to_40_words"))
            } else {
                $("#asset_" + assetid).next().find(".desc_content").text(content);
                for (var i = 0; i < assets.length; i++) {
                    if (assets[i].assetid == assetid) {
                        assets[i].desc = content
                    }
                }
                if (content.length > 0) {
                    $("#asset_" + assetid).next().show();
                    $("#asset_" + assetid).addClass("has_des");
                    $("#asset_" + assetid + " td").css("border-bottom", "0");
                    $("#asset_" + assetid + " .edit_order_desc a").text(i18n("edit_description"))
                } else {
                    $("#asset_" + assetid + " td").css("border-bottom", "1px solid #E9E9E9");
                    $("#asset_" + assetid).next().hide();
                    $("#asset_" + assetid).removeClass("has_des");
                    $("#asset_" + assetid + " .edit_order_desc a").text(i18n("add_description"))
                }
                Popup.hide()
            }
        });
        $(document).on("input", "#j_pupup_add_desc .addDesWrapper textarea", function() {
            $("#j_pupup_add_desc .addDesCount").text($(this).val().length + "/40")
        });
        $(document).on("click", ".overpage-del", function() {
            delete selected[$(this).data("id")];
            $(this).parent().remove();
            update_overpage(true);
            update_selected_style();
            update_select_all_state()
        });
        gallery.init()
    };
    update_bot({
        polling: true,
        onStateChange: function() {
            setTimeout(function() {
                refresh_inventory()
            }, 5e3)
        },
        onBotStatusClose: function() {
            refresh_inventory()
        }
    });
    window.showPunishRemain = function(ele, punishEndTime) {
        var now = Date.now() / 1e3;
        if (punishEndTime <= now) {
            $(ele).attr("data-content", "");
            return
        }
        var hours = Math.floor((punishEndTime - now) / 3600);
        var minutes = Math.ceil((punishEndTime - now) % 3600 / 60);
        var text = i18n("undelivered_notice", {
            hours: hours,
            minutes: minutes
        });
        $(ele).attr("data-content", text)
    }
    ;
    return {
        init: init
    }
};
var selling = function(total_count) {
    var total_count = total_count;
    var game = g.game;
    var sell_orders = [];
    var _MAX_PRICE = BuffConfig.MAX_SELL_PRICE;
    var _MIN_PRICE = BuffConfig.MIN_PRICE;
    var should_update_fee = false;
    var update_fee_timer = null;
    var asset_info = {};
    var sell_order_use_coupon_map = {};
    var coupon_use_map = {};
    var not_use_coupon_value = "false";
    var update_select_all_state = function() {
        var count = $("#j_list_card li.on").length;
        $(".w-Checkbox[name=select-all] span").html('<i class="icon icon_checkbox"></i>' + i18n("all") + " (" + count + "/" + total_count + ")");
        if (count < 1) {
            $(".w-Checkbox[name=select-all] span").removeClass("on");
            $(".w-Checkbox[name=select-all]").attr({
                value: ""
            })
        }
    };
    var check_price_value = sellingPricing().check_price_value;
    var update_fee = function() {
        clearTimeout(update_fee_timer);
        jQuery.xhrPool.abort("/api/market/batch/fee");
        update_fee_timer = setTimeout(function() {
            var prices = [];
            var indices = [];
            var total_price = 0;
            var total_fee = 0;
            var coupon_ids = [];
            for (var i = 0; i < sell_orders.length; i++) {
                if (sell_orders[i].price > 0) {
                    if (check_price_value(sell_orders[i].price, false, sell_orders[i].origin_price) == false) {
                        return
                    }
                    if (!sell_orders[i].has_market_min_price) {
                        prices.push(sell_orders[i].price);
                        indices.push(i);
                        total_price += sell_orders[i].price;
                        if (sell_order_use_coupon_map[sell_orders[i].sell_order_id] != not_use_coupon_value) {
                            coupon_ids.push(sell_order_use_coupon_map[sell_orders[i].sell_order_id])
                        } else {
                            coupon_ids.push("")
                        }
                    } else {
                        total_price += sell_orders[i].income
                    }
                }
            }
            if (prices.length < 1) {
                $("#j_popup_selling_change_preview span.sale_fee").html(formatPriceYuan(total_fee));
                $("#j_popup_selling_change_preview span.real_income").html(formatPriceYuan(total_price - total_fee));
                $("#j_popup_selling_change_preview span.real_income_custom").html(formatPriceNormalCustom(total_price - total_fee));
                return
            }
            $("#j_popup_selling_change_preview a.confirm").addClass("i_Btn_disabled");
            sendRequest("/api/market/batch/fee", {
                data: {
                    game: game,
                    prices: prices.join(","),
                    cdkey_ids: coupon_ids.join(",")
                },
                dataType: "json",
                method: "GET",
                showLoading: false,
                success: function(data) {
                    if (data.code == "OK") {
                        $("#j_popup_selling_change_preview a.confirm").removeClass("i_Btn_disabled");
                        total_fee += parseFloat(data.data.total_fee);
                        $("#j_popup_selling_change_preview span.sale_fee").html(formatPriceYuan(total_fee));
                        $("#j_popup_selling_change_preview span.real_income").html(formatPriceYuan(total_price - parseFloat(total_fee)));
                        $("#j_popup_selling_change_preview span.real_income_custom").html(formatPriceNormalCustom(total_price - parseFloat(total_fee)));
                        $("#j_popup_selling_change_preview input[name=income]").each(function() {
                            var index = $(this).data("index") - 1;
                            if (indices.indexOf(index) != -1) {
                                if (!$(this).is(":focus")) {
                                    sell_orders[index].income = sell_orders[index].price - parseFloat(data.data.fees[indices.indexOf(index)]);
                                    $(this).val(sell_orders[index].income.toFixed(2));
                                    $(this).parents("tr").find(".sell-income-custom").text(formatPriceNormalCustom(sell_orders[index].income, true));
                                    $(this).removeClass("i_Text_error")
                                }
                            }
                        });
                        update_fee_discount_tag()
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                },
                error: function(resp) {
                    if (resp.statusText != "abort") {
                        Buff.toast(i18n("acquisition_fee_failed_please_try"))
                    }
                }
            })
        }, 500)
    };
    var update_fee_discount_tag = function() {
        var order_use_coupon = false;
        for (var order_id in sell_order_use_coupon_map) {
            if (sell_order_use_coupon_map[order_id] && sell_order_use_coupon_map[order_id] != not_use_coupon_value) {
                order_use_coupon = true;
                break
            }
        }
        if (order_use_coupon) {
            $("#discount_icon").show()
        } else {
            $("#discount_icon").hide()
        }
    };
    var hide_fee_discount_sel = function(sel_ids) {
        sel_ids.forEach(function(sel_id) {
            $("#" + sel_id).hide()
        })
    };
    var init = function() {
        gameNavigator.setKeepParams(["mode"]);
        update_select_all_state();
        $(document).on("click", "#j_list_card > ul > li", function() {
            $(this).toggleClass("on");
            update_select_all_state()
        });
        $(".w-Checkbox[name=select-all]").change(function() {
            var value = $(this).attr("value");
            if (value == "selectall") {
                $("#j_list_card > ul > li").addClass("on")
            } else {
                $("#j_list_card > ul > li").removeClass("on")
            }
            update_select_all_state()
        });
        $("#cancel-order").click(function() {
            sell_orders = [];
            $("#j_list_card > ul > li.on").each(function() {
                sell_orders.push({
                    sell_order_id: $(this).data("orderid"),
                    price: parseFloat($(this).data("price"))
                })
            });
            if (sell_orders.length < 1) {
                Buff.toast(i18n("please_select_the_you_want"));
                return
            }
            Buff.alert({
                title: i18n("the_shelves"),
                message: $(this).data("mode") === "manual" ? i18n("determine_the_selected_accessories_to") : i18n("consignment_goods_shelf_will_be"),
                success: function() {
                    var ids = [];
                    for (var i = 0; i < sell_orders.length; i++) {
                        ids.push(sell_orders[i]["sell_order_id"])
                    }
                    var doCancel = function() {
                        sendRequest("/api/market/sell_order/cancel", {
                            data: {
                                game: game,
                                sell_orders: ids
                            },
                            method: "POST",
                            processData: false,
                            timeout: Math.max(5e3, 1e3 * ids.length),
                            success: function(data) {
                                if (data.code == "OK") {
                                    var success = 0;
                                    var fail = 0;
                                    for (orderid in data.data) {
                                        if (data.data[orderid] == "OK") {
                                            success += 1
                                        } else {
                                            fail += 1
                                        }
                                    }
                                    if (success == ids.length) {
                                        Buff.toast(i18n("shelves_successful"), {
                                            type: "success"
                                        });
                                        window.location.reload()
                                    } else {
                                        var html = "<p>" + success + i18n("_piece_of_goods_off");
                                        html += "<p>" + fail + i18n("_piece_of_goods_has");
                                        Buff.alert({
                                            title: i18n("off_the_shelves_results"),
                                            message: html,
                                            hideCancel: true,
                                            success: function() {
                                                window.location.reload()
                                            }
                                        })
                                    }
                                    $("#j_list_card > ul > li").removeClass("on")
                                }
                            }
                        })
                    };
                    sendRequest("/api/market/sell_order/cancel/check_rate_limit", {
                        data: {
                            game: game,
                            sell_orders: ids
                        },
                        method: "POST",
                        processData: false,
                        timeout: Math.max(5e3, 1e3 * ids.length),
                        success: function(data) {
                            if (data.code == "OK") {
                                doCancel()
                            } else if (data.code == "Request Rate Will Be Limited") {
                                Buff.alert({
                                    title: i18n("the_shelves"),
                                    message: data.error,
                                    success: doCancel
                                })
                            } else {
                                Buff.toast(data.error, {
                                    type: "error"
                                })
                            }
                        }
                    })
                }
            })
        });
        $(document).on("click", "#j_list_card .icon_recommend,#j_list_card .icon_fav2", function(event) {
            var that = this;
            sendRequest("/api/market/sell_order/featured", {
                data: {
                    sell_order: $(this).data("orderid"),
                    featured: $(this).hasClass("on") ? 0 : 1
                },
                dataType: "json",
                method: "PUT",
                showLoading: false,
                success: function(data) {
                    if (data.code == "Featured Limit Excceed") {
                        Buff.alert({
                            title: i18n("the_recommended_bit_is_already"),
                            message: data.error,
                            hideCancel: true
                        });
                        return
                    }
                    if (data.code == "OK") {
                        $(that).toggleClass("on");
                        if ($(that).hasClass("on")) {
                            $(that).attr("data-title", i18n("cancel_recommend"));
                            $("#j_fixedtip h3").text(i18n("cancel_recommend"))
                        } else {
                            $(that).attr("data-title", i18n("the_set_of_recommended_items"));
                            $("#j_fixedtip h3").text(i18n("the_set_of_recommended_items"))
                        }
                        return
                    }
                    Buff.toast(data.error, {
                        type: "error"
                    })
                }
            });
            event.stopPropagation()
        });
        init_change_price()
    };
    var init_change_price = function() {
        var show_change_price_popup = function() {
            if (sell_orders.length < 1) {
                Buff.toast(i18n("select_to_change_the_price"));
                return
            }
            var get_coupons = function(game, state, callback) {
                sendRequest("/api/activity/coupon/my/", {
                    method: "GET",
                    data: {
                        game: game,
                        state: "unuse",
                        coupon_type: "fee_discount",
                        only_coupon: 1
                    },
                    dataType: "json",
                    showLoading: false,
                    success: function(data) {
                        if (data.code != "OK") {
                            Buff.toast(data.error, {
                                type: "error"
                            });
                            return
                        }
                        var items = data.data.items;
                        if (items.length < 1) {
                            callback([], true);
                            return
                        }
                        var coupon_list = [];
                        var using_coupon_map = {};
                        items.forEach(function(coupon) {
                            if (coupon.state != "using") {
                                coupon_list.push({
                                    label: coupon.name,
                                    value: coupon.id,
                                    desc: coupon.expire_time.message + "&nbsp" + formatTimestamp(coupon.expire_time.time, "YYYY-MM-DD")
                                })
                            } else {
                                using_coupon_map[coupon.id] = coupon
                            }
                        });
                        coupon_list.push({
                            value: not_use_coupon_value,
                            label: i18n("not_use_coupon"),
                            desc: ""
                        });
                        callback(coupon_list, using_coupon_map, Object.keys(using_coupon_map).length < 0 && coupon_list.length <= 1)
                    }
                })
            };
            sendRequest("/market/sell_order/change_preview", {
                method: "POST",
                data: {
                    game: game,
                    sell_orders: sell_orders
                },
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        $("#popup-container").html(data.data);
                        initCustomCurrency($("#j_popup_selling_change_preview"));
                        Popup.show("j_popup_selling_change_preview");
                        Buff.pricePatten("input[name=price]");
                        Buff.pricePatten("input[name=income]");
                        update_order_price();
                        var order_coupon_info_map = {};
                        sell_orders.forEach(function(item) {
                            var order_id = item.sell_order_id;
                            var order_item = $("#sell_order_" + order_id);
                            if (order_item.data("coupon-infos")) {
                                order_coupon_info_map[order_id] = order_item.data("coupon-infos")
                            }
                        });
                        get_coupons(game, "unuse", function(unuse_coupon_list, using_coupon_map, empty_coupon) {
                            coupon_use_map = {};
                            sell_order_use_coupon_map = {};
                            var row_sel_ids = [];
                            var sel_id_prefix = "coupon_sel_";
                            sell_orders.forEach(function(item) {
                                row_sel_ids.push(sel_id_prefix + item.sell_order_id)
                            });
                            if (empty_coupon) {
                                hide_fee_discount_sel(row_sel_ids);
                                return
                            }
                            var coupon_list = {};
                            sell_orders.forEach(function(item) {
                                var order_id = item.sell_order_id;
                                if (order_coupon_info_map[order_id]) {
                                    order_coupon_info_map[order_id].forEach(function(coupon_info) {
                                        if (coupon_info.coupon_type == "fee_discount") {
                                            var coupon_all_info = using_coupon_map[coupon_info.cdkey_id];
                                            coupon_list[coupon_info.cdkey_id] = {
                                                value: coupon_info.cdkey_id,
                                                label: coupon_all_info.name,
                                                desc: coupon_all_info.expire_time.message + "&nbsp" + formatTimestamp(coupon_all_info.expire_time.time, "YYYY-MM-DD")
                                            };
                                            coupon_use_map[coupon_info.cdkey_id] = {
                                                state: false,
                                                value: coupon_info.cdkey_id,
                                                is_expired: coupon_all_info.expire_time.is_expired,
                                                original_order_id: order_id
                                            };
                                            sell_order_use_coupon_map[order_id] = coupon_info.cdkey_id
                                        }
                                    })
                                }
                            });
                            if (unuse_coupon_list.length <= 1 && Object.keys(order_coupon_info_map).length == 0) {
                                hide_fee_discount_sel(row_sel_ids);
                                return
                            }
                            unuse_coupon_list.forEach(function(coupon) {
                                coupon_list[coupon.value] = coupon;
                                coupon_use_map[coupon.value] = {
                                    state: true,
                                    value: coupon.value,
                                    is_expired: false
                                }
                            });
                            var get_coupon_select_options = function(sel_id) {
                                var options = [];
                                var order_id = $("#" + sel_id).attr("order_id");
                                var sel_coupon_value = sell_order_use_coupon_map[order_id];
                                var add_not_use_coupon = false;
                                var cur_index = -1;
                                var default_index = -1;
                                for (var k in coupon_list) {
                                    var coupon = coupon_list[k];
                                    if (coupon_use_map[coupon.value]["state"] || sel_coupon_value == coupon.value) {
                                        if (coupon.value == not_use_coupon_value) {
                                            add_not_use_coupon = true
                                        }
                                        options.push({
                                            value: coupon.value,
                                            label: coupon.label,
                                            desc: coupon.desc
                                        });
                                        cur_index += 1;
                                        if (sel_coupon_value == coupon.value) {
                                            default_index = cur_index
                                        }
                                    }
                                }
                                if (!add_not_use_coupon && options.length > 0) {
                                    options.push({
                                        value: not_use_coupon_value,
                                        label: i18n("not_use_coupon"),
                                        desc: ""
                                    })
                                }
                                if (options.length <= 1) {
                                    options = []
                                }
                                var coupon_sel_option = {
                                    placeholder: i18n("please_choose_coupon"),
                                    options: options
                                };
                                if (default_index != -1) {
                                    coupon_sel_option.defaultIndex = default_index
                                }
                                return coupon_sel_option
                            };
                            var coupon_sel_callback = function(cur_sel_coupon, sel_id) {
                                var $this = $("#" + sel_id);
                                var order_id = $this.attr("order_id");
                                var pre_sel_coupon = $this.attr("data-value");
                                var coupon_info = coupon_use_map[pre_sel_coupon];
                                if (pre_sel_coupon && coupon_info.is_expired && coupon_info.original_order_id == order_id) {
                                    return new Promise(function(resolve, reject) {
                                        Buff.alert({
                                            message: i18n("expired_coupon_switch"),
                                            cancel: function() {
                                                reject()
                                            },
                                            success: function() {
                                                sell_order_use_coupon_map[order_id] = cur_sel_coupon;
                                                coupon_use_map[cur_sel_coupon]["state"] = false;
                                                console.log(coupon_use_map, coupon_list);
                                                delete coupon_use_map[pre_sel_coupon];
                                                delete coupon_list[pre_sel_coupon];
                                                console.log(coupon_use_map, coupon_list);
                                                update_fee();
                                                resolve()
                                            }
                                        })
                                    }
                                    )
                                } else {
                                    sell_order_use_coupon_map[order_id] = cur_sel_coupon;
                                    if (pre_sel_coupon) {
                                        coupon_use_map[pre_sel_coupon]["state"] = true
                                    }
                                    coupon_use_map[cur_sel_coupon]["state"] = false;
                                    return new Promise(function(resolve, reject) {
                                        update_fee();
                                        resolve()
                                    }
                                    )
                                }
                            };
                            row_sel_ids.forEach(function(sel_id) {
                                var coupon_sel_option = get_coupon_select_options(sel_id);
                                Buff.initCouponSelect(sel_id, coupon_sel_option, coupon_sel_callback);
                                update_fee_discount_tag()
                            });
                            row_sel_ids.forEach(function(sel_id) {
                                $("body").on("change", "#" + sel_id, function() {
                                    var $this_id = $(this).attr("id");
                                    row_sel_ids.forEach(function(sel_id) {
                                        if (sel_id == $this_id) {
                                            return
                                        }
                                        var coupon_sel_option = get_coupon_select_options(sel_id);
                                        Buff.initCouponSelect(sel_id, coupon_sel_option, coupon_sel_callback)
                                    })
                                })
                            })
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        };
        $("#change-price").click(function() {
            sell_orders = [];
            $("#j_list_card > ul > li.on").each(function() {
                sell_orders.push({
                    sell_order_id: $(this).data("orderid"),
                    price: "",
                    income: "",
                    has_market_min_price: false,
                    goods_id: $(this).data("goodsid")
                });
                asset_info[$(this).data("orderid")] = {
                    name: $(this).data("goods-name"),
                    icon_url: $(this).data("icon-url"),
                    tags: $(this).data("goods-tags"),
                    appid: $(this).data("appid"),
                    assetid: $(this).data("assetid").toString()
                }
            });
            show_change_price_popup()
        });
        $(document).on("click", ".change-price-btn", function() {
            sell_orders = [{
                sell_order_id: $(this).data("orderid"),
                price: "",
                income: "",
                has_market_min_price: false,
                goods_id: $(this).data("goodsid")
            }];
            asset_info[$(this).data("orderid")] = {
                name: $(this).data("goods-name"),
                icon_url: $(this).data("icon-url"),
                tags: $(this).data("goods-tags"),
                appid: $(this).data("appid")
            };
            show_change_price_popup()
        });
        var update_order_price = function() {
            $("#j_popup_selling_change_preview tr.assets-item input[name=price]").each(function() {
                var index = $(this).data("index") - 1;
                var price = parseFloat($(this).val());
                if (isNaN(price) || $(this).val().length == 0) {
                    sell_orders[index].price = ""
                } else {
                    sell_orders[index].price = price
                }
                sell_orders[index].has_market_min_price = parseFloat($(this).data("market-min-price")) > 0
            });
            $("#j_popup_selling_change_preview tr.assets-item input[name=income]").each(function() {
                var index = $(this).data("index") - 1;
                var income = parseFloat($(this).val());
                if (isNaN(income) || $(this).val().length == 0) {
                    sell_orders[index].income = ""
                } else {
                    sell_orders[index].income = income
                }
            })
        };
        $(document).on("change", ".w-Checkbox[name=combine]", function() {
            var value = $(this).attr("value");
            if (value == "combine") {
                var group_key_data = $("#j_popup_selling_change_preview").data("group-key");
                for (var group_key in group_key_data) {
                    if (group_key_data[group_key].assetids.length > 1) {
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + ":not(:first)").hide();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + ":first .name-cont p.num").remove();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + ":first .name-cont").append('<p class="num c_Gray" style="font-size: 13px;"> ×' + group_key_data[group_key].assetids.length + "</p>");
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " input").val("");
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .sell-price-custom").html("");
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .sell-income-custom").html("");
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .pic-cont .item-count").show();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key).next(".des_row").hide();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " td").css("border-bottom", "1px solid #E9E9E9");
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .edit_order_desc a").hide();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .edit_order_desc .w-Select-coupon").hide();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .paint-wear").hide();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .csgo_sticker_inline").hide();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .group_key_notice").show();
                        $("#j_popup_selling_change_preview tr.group_key_" + group_key + " div.notes").hide()
                    }
                }
                update_order_price();
                update_fee()
            } else {
                $("#j_popup_selling_change_preview tr.assets-item").show();
                $("#j_popup_selling_change_preview tr.assets-item .edit_order_desc a").show();
                $("#j_popup_selling_change_preview tr.assets-item .edit_order_desc .w-Select-coupon").show();
                $("#j_popup_selling_change_preview tr.assets-item .paint-wear").show();
                $("#j_popup_selling_change_preview tr.assets-item .csgo_sticker_inline").show();
                $("#j_popup_selling_change_preview tr.assets-item.has_des").next().show();
                $("#j_popup_selling_change_preview tr.assets-item.has_des td").css("border-bottom", "0");
                $("#j_popup_selling_change_preview tr.assets-item .name-cont p.num").remove();
                $("#j_popup_selling_change_preview tr.assets-item .pic-cont .item-count").hide();
                $("#j_popup_selling_change_preview tr.assets-item .group_key_notice").hide();
                $("#j_popup_selling_change_preview tr.assets-item div.notes").show()
            }
        });
        $(document).on("input", "#j_popup_selling_change_preview input[name=price]", function() {
            var index = $(this).data("index") - 1;
            var input_price = $(this).val();
            var input_income = $(this).parents("tr").find("input[name=income]").val();
            var price = parseFloat(input_price);
            var income = parseFloat(input_income);
            var market_min_price = parseFloat($(this).data("market-min-price"));
            if (market_min_price > 0 && price < market_min_price) {
                price = market_min_price
            }
            if (check_price_value($(this).val(), false, $(this).attr("value"))) {
                $(this).removeClass("i_Text_error")
            } else {
                $(this).addClass("i_Text_error")
            }
            sell_orders[index].price = price;
            sell_orders[index].origin_price = $(this).attr("value");
            sell_orders[index].income = income;
            sell_orders[index].has_market_min_price = market_min_price > 0;
            var value = $(".w-Checkbox[name=combine]").attr("value");
            if (value == "combine") {
                var group_key_data = $("#j_popup_selling_change_preview").data("group-key");
                var group_key = $(this).data("group-key");
                var assetids = group_key_data[group_key].assetids;
                for (var i = 0; i < sell_orders.length; i++) {
                    if (assetids.indexOf(asset_info[sell_orders[i].sell_order_id].assetid) > -1) {
                        sell_orders[i].price = sell_orders[index].price;
                        sell_orders[i].income = sell_orders[index].income;
                        sell_orders[i].has_market_min_price = sell_orders[index].has_market_min_price
                    }
                }
                $("#j_popup_selling_change_preview tr.group_key_" + group_key + " input[name=price]").val(input_price);
                $("#j_popup_selling_change_preview tr.group_key_" + group_key + " input[name=income]").val(input_income);
                $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .sell-price-custom").html(price ? formatPriceNormalCustom(price, true) : "");
                $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .sell-price-income").html(income ? formatPriceNormalCustom(income, true) : "");
                if ($(this).hasClass("i_Text_error")) {
                    $("#j_popup_selling_change_preview tr.group_key_" + group_key + " input[name=price]").addClass("i_Text_error");
                    $("#j_popup_selling_change_preview tr.group_key_" + group_key + " input[name=income]").addClass("i_Text_error")
                } else {
                    $("#j_popup_selling_change_preview tr.group_key_" + group_key + " input[name=price]").removeClass("i_Text_error");
                    $("#j_popup_selling_change_preview tr.group_key_" + group_key + " input[name=income]").removeClass("i_Text_error");
                    $("#j_popup_selling_change_preview tr.group_key_" + group_key + " .cannot-quick-pricing").remove()
                }
            }
            $(this).parents("tr").find(".sell-price-custom").html(price ? formatPriceNormalCustom(price, true) : "");
            update_fee()
        });
        $(document).on("change", "#j_popup_selling_change_preview input[name=price]", function() {
            if (check_price_value($(this).val(), true, $(this).attr("value"))) {
                update_fee()
            }
        });
        var selling_pricing = sellingPricing();
        $(document).on("input", "#j_popup_selling_change_preview input[name=income]", function() {
            var row = $(this).parents("tr");
            var sell_order_id = $(row).attr("id").replace("sell_order_change_", "");
            var coupon_id = sell_order_use_coupon_map[sell_order_id] != "false" ? sell_order_use_coupon_map[sell_order_id] : "";
            selling_pricing.get_price_from_income(row, coupon_id);
            var income = $(this).val();
            $(this).parents("tr").find(".sell-income-custom").html(income ? formatPriceNormalCustom(income, true) : "")
        });
        $(document).on("change", "#j_popup_selling_change_preview input[name=income]", function() {
            if (check_price_value($(this).val(), true)) {
                var row = $(this).parents("tr");
                var sell_order_id = $(row).attr("id").replace("sell_order_change_", "");
                var coupon_id = sell_order_use_coupon_map[sell_order_id] != "false" ? sell_order_use_coupon_map[sell_order_id] : "";
                selling_pricing.get_price_from_income(row, coupon_id)
            }
        });
        $(document).on("click", "#j_popup_selling_change_preview #quick-pricing", function() {
            selling_pricing.quick_pricing($("#j_popup_selling_change_preview"));
            update_fee()
        });
        $(document).on("click", "#j_popup_selling_change_preview a.confirm:not(.i_Btn_disabled)", function() {
            for (var i = 0; i < sell_orders.length; i++) {
                var sell_order = sell_orders[i];
                if (check_price_value(sell_order.price, true, sell_order.origin_price) == false) {
                    return
                }
                var content = $("#sell_order_change_" + sell_order.sell_order_id).next().find(".desc_content").text();
                sell_order.desc = content
            }
            selling_pricing.find_unusual_price($("#j_popup_selling_change_preview"), function() {
                var sell_orders_with_coupon = [];
                sell_orders.forEach(function(item) {
                    var cdkey_id = sell_order_use_coupon_map[item.sell_order_id] || "";
                    if (cdkey_id != not_use_coupon_value) {
                        item["cdkey_id"] = cdkey_id
                    }
                    sell_orders_with_coupon.push(item)
                });
                sendRequest("/api/market/sell_order/change", {
                    method: "POST",
                    data: {
                        game: game,
                        sell_orders: sell_orders
                    },
                    timeout: Math.max(5e3, 1e3 * sell_orders.length),
                    success: function(data) {
                        if (data.code == "OK") {
                            var success = 0;
                            var failures = [];
                            for (var i = 0; i < sell_orders.length; i++) {
                                var orderid = sell_orders[i].sell_order_id;
                                var result = data.data[orderid];
                                if (result == "OK") {
                                    success += 1;
                                    $("#sell_order_" + orderid).find(".sell_order_price").html(formatPriceCustom(sell_orders[i].price));
                                    $("#sell_order_" + orderid).data("price", sell_orders[i].price)
                                } else {
                                    failures.push({
                                        order: sell_orders[i],
                                        reason: result,
                                        info: asset_info[orderid]
                                    })
                                }
                            }
                            if (failures.length > 0) {
                                Popup.hide();
                                var html = template_render("result_pat", {
                                    failures: failures,
                                    success: success
                                });
                                $("#popup-container").html(html);
                                Popup.show("j_popup_charge-result")
                            } else {
                                if ($(".c_Yellow.offline_tips").is(":visible")) {
                                    Popup.hide();
                                    Buff.alert({
                                        title: i18n("the_modified_price_of_success"),
                                        message: i18n("add_in_the_buyers_payment"),
                                        hideCancel: true,
                                        rememberDismiss: "deliver_tips",
                                        success: function(dismiss) {
                                            if (dismiss) {
                                                Buff.toast(i18n("the_modified_price_of_success"), {
                                                    type: "success"
                                                });
                                                Popup.hide()
                                            }
                                            setTimeout(function() {
                                                window.location.reload()
                                            }, 2e3)
                                        }
                                    })
                                } else {
                                    Buff.toast(i18n("the_modified_price_of_success"), {
                                        type: "success"
                                    });
                                    Popup.hide();
                                    setTimeout(function() {
                                        window.location.reload()
                                    }, 2e3)
                                }
                                $("#select-all").removeClass("all");
                                $("#j_list_card > ul > li").removeClass("on")
                            }
                            update_select_all_state()
                        } else if (data.code == "Invalid Argument") {
                            Buff.toast(data.error || data.code, {
                                type: "warning"
                            })
                        } else {
                            Buff.toast(data.error || i18n("change_price_of_failure"), {
                                type: "error"
                            })
                        }
                    }
                })
            }, true)
        });
        $(document).on("click", ".edit_order_desc a", function() {
            var sell_order_id = $(this).data("orderid");
            Popup.show("j_pupup_add_desc");
            var content = $("#sell_order_change_" + sell_order_id).next().find(".desc_content").text();
            $("#j_pupup_add_desc .addDesCount").text(content.length + "/40");
            $("#j_pupup_add_desc .addDesWrapper textarea").val(content);
            $("#j_pupup_add_desc .i_Btn_main").data("orderid", sell_order_id)
        });
        $(document).on("click", "#j_pupup_add_desc .i_Btn_main", function() {
            var sell_order_id = $(this).data("orderid");
            var content = $("#j_pupup_add_desc .addDesWrapper textarea").val();
            if (content.length > 40) {
                Buff.toast(i18n("the_content_of_the_input"))
            } else {
                $("#sell_order_change_" + sell_order_id).next().find(".desc_content").text(content);
                for (var i = 0; i < sell_orders.length; i++) {
                    if (sell_orders[i].sell_order_id == sell_order_id) {
                        sell_orders[i].desc = content
                    }
                }
                if (content.length > 0) {
                    $("#sell_order_change_" + sell_order_id).next().show();
                    $("#sell_order_change_" + sell_order_id).addClass("has_des");
                    $("#sell_order_change_" + sell_order_id + " td").css("border-bottom", "0");
                    $("#sell_order_change_" + sell_order_id + " .edit_order_desc a").text(i18n("edit_the_description"))
                } else {
                    $("#sell_order_change_" + sell_order_id + " td").css("border-bottom", "1px solid #E9E9E9");
                    $("#sell_order_change_" + sell_order_id).next().hide();
                    $("#sell_order_change_" + sell_order_id).removeClass("has_des");
                    $("#sell_order_change_" + sell_order_id + " .edit_order_desc a").text(i18n("add_a_description"))
                }
                Popup.hide()
            }
        });
        $(document).on("input", "#j_pupup_add_desc .addDesWrapper textarea", function() {
            $("#j_pupup_add_desc .addDesCount").text($(this).val().length + "/40")
        })
    };
    return {
        init: init,
        init_change_price: init_change_price
    }
};
var sellingToDeliver = function(bill_order_ids, total_count) {
    var game = g.game;
    var bill_order_ids = bill_order_ids;
    var bill_orders = [];
    var update_select_all_state = function() {
        var count = $(".deliver-order.TO_DELIVER .pic-cont.on").length;
        $(".w-Checkbox[name=select-all] span").html('<i class="icon icon_checkbox"></i>' + i18n("all") + " (" + count + "/" + total_count + ")");
        if (count < 1) {
            $(".w-Checkbox[name=select-all] span").removeClass("on");
            $(".w-Checkbox[name=select-all]").attr({
                value: ""
            })
        }
    };
    var _format = function(num) {
        if (num == 0) {
            return "00"
        } else if (num > 0 && num < 10) {
            return "0" + num
        }
        return "" + num
    };
    var countDownTime = function(poll) {
        $("span.count-down").each(function() {
            var expire = $(this).data("expire");
            $(this).data("expire", expire - 1);
            expire = parseInt(expire);
            var formatted = i18n("delivery_timeout");
            if (expire > 0) {
                var m = moment.duration(expire, "seconds");
                formatted = _format(parseInt(m.asHours())) + ":" + _format(m.minutes()) + ":" + _format(m.seconds())
            }
            $(this).html(formatted)
        });
        if (poll == true)
            setTimeout(function() {
                countDownTime(true)
            }, 1e3)
    };
    countDownTime(true);
    var refreshOrderStatus = function(poll) {
        sendRequest("/market/sell_order/to_deliver/batch", {
            data: {
                game: game,
                bill_orders: bill_order_ids.join(",")
            },
            showLoading: false,
            showError: false,
            method: "GET",
            dataType: "json",
            success: function(data) {
                if (data.code == "OK") {
                    $("table.list_tb tbody").html(data.data);
                    initCustomCurrency($("table.list_tb tbody"));
                    for (var i = 0; i < bill_orders.length; i++) {
                        $("#bill_order_" + bill_orders[i] + " .pic-cont").addClass("on")
                    }
                    countDownTime();
                    if (poll == true)
                        setTimeout(function() {
                            refreshOrderStatus(true)
                        }, 5e3)
                } else {
                    Buff.toast(data.error)
                }
            }
        })
    };
    if (bill_order_ids.length > 0)
        refreshOrderStatus(true);
    update_bot({
        polling: true,
        onStateChange: function() {
            refreshOrderStatus()
        }
    });
    var init = function() {
        update_select_all_state();
        $(".w-Checkbox[name=select-all]").change(function() {
            var value = $(this).attr("value");
            if (value == "selectall") {
                $(".deliver-order.TO_DELIVER .pic-cont").addClass("on")
            } else {
                $(".deliver-order.TO_DELIVER .pic-cont").removeClass("on")
            }
            bill_orders = [];
            $(".deliver-order.TO_DELIVER .pic-cont.on").each(function() {
                var orderid = $(this).data("orderid");
                bill_orders.push(orderid)
            });
            update_select_all_state()
        });
        $("#deliver").click(function() {
            Buff.alert({
                title: i18n("prompt"),
                message: i18n("beware_of_phishing_scams_please"),
                cancelText: i18n("to_check"),
                confirmText: i18n("i_know"),
                rememberDismiss: "fraud_notice",
                hide_popup_after_cancel: false,
                success: doDeliver,
                cancel: function() {
                    openPageOnNewTab("https://steamcommunity.com/dev/apikey")
                }
            })
        });
        var doDeliver = function() {
            bill_orders = [];
            $(".deliver-order.TO_DELIVER .pic-cont.on").each(function() {
                var orderid = $(this).data("orderid");
                bill_orders.push(orderid)
            });
            doDeliverBillOrders(bill_orders)
        };
        var doDeliverBillOrders = function(bill_orders) {
            if (bill_orders.length < 1) {
                Buff.toast(i18n("please_select_to_ship_the"));
                return
            }
            sendRequest("/api/market/bill_order/deliver", {
                data: {
                    game: game,
                    bill_orders: bill_orders
                },
                dataType: "json",
                method: "POST",
                success: function(data) {
                    if (data.code == "OK") {
                        bot_trades = {};
                        bot_trades[data.data.id] = data.data;
                        update_bot();
                        refreshOrderStatus()
                    } else if (data.code == "Steam Trade URL Binding Required") {
                        Buff.alert({
                            title: i18n("prompt"),
                            message: i18n("unbound_steam_trading_link_whether"),
                            success: function() {
                                window.open("/user-center/profile", "_blank")
                            },
                            cancel: function() {
                                Buff.toast(i18n("the_quote_failed_to_send"))
                            }
                        })
                    } else {
                        Buff.toast(i18n("the_quote_failed_to_send") + data.error)
                    }
                }
            })
        };
        $(document).on("click", ".cancel-deliver", function(e) {
            e.stopPropagation();
            var bill_order_id = $(this).data("orderid");
            sendRequest("/api/market/bill_order/deliver/cancel/preview", {
                data: {
                    game: game,
                    bill_order_id: bill_order_id
                },
                dataType: "json",
                method: "GET",
                success: function(data) {
                    if (data.code == "OK") {
                        Buff.alert({
                            title: i18n("cancel_the_shipment"),
                            message: data.data.message,
                            cancelText: i18n("i_think_again"),
                            confirmText: i18n("cancel_the_shipment"),
                            success: function() {
                                sendRequest("/api/market/bill_order/deliver/cancel", {
                                    data: {
                                        game: game,
                                        bill_order_id: bill_order_id
                                    },
                                    dataType: "json",
                                    method: "POST",
                                    success: function(data) {
                                        if (data.code == "OK") {
                                            refreshOrderStatus();
                                            Buff.toast(i18n("cancel_delivery_success"))
                                        } else {
                                            Buff.toast(data.error, {
                                                type: "error"
                                            })
                                        }
                                    }
                                })
                            }
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        });
        $(document).on("click", ".replace-asset", function(e) {
            e.stopPropagation();
            var bill_order_id = $(this).data("orderid");
            showReplaceAssetPreview(bill_order_id, false)
        });
        $(document).on("click", ".refresh-inventory", function(e) {
            $(this).hide();
            $("#j_popup_replace_asset .packlist").showLoading();
            $("#j_popup_replace_asset").find("#deliver-confirm").addClass("i_Btn_disabled");
            $("#j_popup_replace_asset").find("#fee").html(formatPriceNormalYuan(0));
            $("#j_popup_replace_asset").find("#total_price").html(formatPriceYuan(0));
            $("#j_popup_replace_asset").find("#total_price_custom").html(formatPriceNormalCustom(0));
            var bill_order_id = $(this).data("orderid");
            showReplaceAssetPreview(bill_order_id, true)
        });
        var showReplaceAssetPreview = function(bill_order_id, is_refresh) {
            var force_update = is_refresh ? 1 : undefined;
            sendRequest("/api/market/bill_order/replace_asset/preview", {
                method: "GET",
                timeout: BuffConfig.STEAM_TIMEOUT,
                data: {
                    bill_order_id: bill_order_id,
                    force_update: force_update
                },
                showLoading: !is_refresh,
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        return
                    }
                    var html = template_render("replace_asset_pat", data.data);
                    $("#popup-container").html(html);
                    var selected_assetid = null;
                    $("#j_popup_replace_asset").find(".packcard li").click(function() {
                        var assetid = $(this).attr("data-assetid");
                        if ($(this).hasClass("on")) {
                            $(this).removeClass("on");
                            if (selected_assetid == assetid)
                                selected_assetid = null
                        } else {
                            if (selected_assetid && selected_assetid != assetid)
                                return;
                            $(this).addClass("on");
                            selected_assetid = assetid
                        }
                        $("#j_popup_replace_asset").find("#deliver-confirm").data("assetid", selected_assetid);
                        var count = selected_assetid ? 1 : 0;
                        $("#selected-backpack-num").text(count);
                        if (selected_assetid) {
                            $("#j_popup_replace_asset").find("#deliver-confirm").removeClass("i_Btn_disabled")
                        } else {
                            $("#j_popup_replace_asset").find("#deliver-confirm").addClass("i_Btn_disabled")
                        }
                        if (selected_assetid) {
                            $("#j_popup_replace_asset").find(".packcard li").each(function() {
                                if (!$(this).hasClass("on")) {
                                    $(this).find(".mask").css("display", "block")
                                } else {
                                    $(this).find(".mask").hide()
                                }
                            })
                        } else {
                            $("#j_popup_replace_asset").find(".mask").hide()
                        }
                        $("#j_popup_replace_asset").find("#fee").html(formatPriceNormalYuan(count * parseFloat(data.data.bill_order.fee)));
                        $("#j_popup_replace_asset").find("#total_price").html(formatPriceYuan(count * (data.data.bill_order.price - data.data.bill_order.fee)));
                        $("#j_popup_replace_asset").find("#total_price_custom").html(formatPriceNormalCustom(count * (data.data.bill_order.price - data.data.bill_order.fee)))
                    });
                    if (is_refresh) {
                        Popup.hide()
                    }
                    Popup.show("j_popup_replace_asset")
                }
            })
        };
        $(document).on("click", "#j_popup_replace_asset #deliver-confirm", function() {
            if ($(this).hasClass("i_Btn_disabled"))
                return;
            $(this).addClass("i_Btn_disabled");
            var bill_order_id = $(this).data("orderid");
            var assetid = $(this).data("assetid");
            sendRequest("/api/market/bill_order/replace_asset", {
                method: "POST",
                data: {
                    bill_order_id: bill_order_id,
                    assetid: assetid
                },
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        return
                    }
                    Popup.hide();
                    doDeliverBillOrders([bill_order_id])
                }
            })
        });
        $(document).on("click", ".deliver-order.TO_DELIVER", function() {
            $(this).find(".pic-cont").toggleClass("on");
            bill_orders = [];
            $(".deliver-order.TO_DELIVER .pic-cont.on").each(function() {
                var orderid = $(this).data("orderid");
                bill_orders.push(orderid)
            });
            update_select_all_state()
        })
    };
    return {
        init: init
    }
};
var sellingPricing = function() {
    var quick_pricing = function($popup) {
        $popup.find('input[name="price"]').each(function() {
            var price = $(this).data("quick-price");
            if (price > 0) {
                $(this).val(price).trigger("input")
            } else {
                $(this).val("");
                $(this).parents("tr").find('input[name="income"]').val("");
                $(this).trigger("input");
                $(this).parents("tr").find('input[name="income"]').trigger("input");
                var text = $(this).data("error");
                if (text.length < 1)
                    text = i18n("the_goods_can_not_a");
                var text = $("<p />", {
                    class: "c_Gray cannot-quick-pricing"
                }).append($("<small />", {
                    text: text
                })).css({
                    "padding-top": "5px",
                    position: "absolute"
                });
                $(this).parent().append(text)
            }
        })
    };
    var find_unusual_price = function($popup, success, isChange) {
        var inputs = $popup.find('input[name="price"]');
        var prices = [];
        var goods_ids = [];
        for (var i = 0; i < inputs.length; i++) {
            var goods_id = $(inputs[i]).data("goodsid");
            prices.push($(inputs[i]).val());
            goods_ids.push(goods_id)
        }
        sendRequest("/api/market/batch/fee", {
            method: "GET",
            dataType: "json",
            data: {
                game: g.game,
                prices: prices.join(","),
                goods_ids: goods_ids.join(","),
                is_change: isChange ? 1 : 0,
                check_price: 1
            },
            showLoading: false,
            success: function(data) {
                if (data.code !== "OK") {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    return
                }
                if (data.data.unusual) {
                    Buff.alert({
                        title: data.data.title,
                        message: data.data.message,
                        cancelText: data.data.cancel_text,
                        confirmText: data.data.confirm_text,
                        success: function() {
                            success()
                        }
                    })
                } else {
                    success()
                }
            }
        })
    };
    var check_price_value = function(price, toast, origin_price) {
        var _MIN_PRICE = BuffConfig.MIN_PRICE;
        var _MAX_PRICE = BuffConfig.MAX_SELL_PRICE;
        if (typeof price == "string" && price.length == 0 || typeof price == "object" || isNaN(price)) {
            if (toast) {
                Buff.toast(i18n("there_goods_is_not_input"), {
                    type: "error"
                })
            }
            return false
        }
        price = parseFloat(price);
        origin_price = origin_price && parseFloat(origin_price) || 0;
        if (price < _MIN_PRICE) {
            if (toast) {
                Buff.toast(i18n("price_must_be_greater_than") + _MIN_PRICE)
            }
            return false
        }
        return true
    };
    var get_price_from_income_timer = {};
    var get_price_from_income_requests = {};
    var get_price_from_income = function(row, cdkey_ids) {
        var input = $(row).find("input[name=income]");
        var rowid = $(row).attr("id");
        if (check_price_value($(input).val())) {
            $(input).removeClass("i_Text_error")
        } else {
            $(input).addClass("i_Text_error")
        }
        clearTimeout(get_price_from_income_timer[rowid]);
        if (get_price_from_income_requests[rowid])
            get_price_from_income_requests[rowid].abort();
        get_price_from_income_timer[rowid] = setTimeout(function() {
            var income = $(row).find("input[name=income]").val();
            if (check_price_value(income, false)) {
                sendRequest("/api/market/get_prices_from_incomes", {
                    data: {
                        game: g.game,
                        incomes: income,
                        cdkey_ids: cdkey_ids
                    },
                    dataType: "json",
                    method: "GET",
                    showLoading: false,
                    success: function(data) {
                        if (data.code != "OK") {
                            Buff.toast(data.error, {
                                type: "error"
                            });
                            return
                        }
                        $(row).find("input[name=price]").val(data.data.prices[0]).trigger("input")
                    },
                    beforeSend: function(jqXHR, settings) {
                        get_price_from_income_requests[rowid] = jqXHR
                    }
                })
            }
        }, 500)
    };
    $(document).on("input", '.popup input[name="price"]', function() {
        $(this).parent().find(".cannot-quick-pricing").remove()
    });
    return {
        quick_pricing: quick_pricing,
        find_unusual_price: find_unusual_price,
        get_price_from_income: get_price_from_income,
        check_price_value: check_price_value
    }
};
var backpack = function() {
    var game = g.game;
    var items = {};
    var goods_infos = {};
    var asset_info = {};
    var assets = [];
    var selected = {};
    var asset_backpackid = {};
    var _MAX_PRICE = BuffConfig.MAX_SELL_PRICE;
    var _MIN_PRICE = BuffConfig.MIN_PRICE;
    var backpack_count = undefined;
    var visible_backpack_count = undefined;
    var backpack_limit = undefined;
    var total_amount = 0;
    var update_fee_timer = null;
    var get_sorted_selected = function() {
        return Object.keys(selected).sort(function(a, b) {
            return selected[a] - selected[b]
        })
    };
    var update_select_all_state = function() {
        var count = $("#j_list_card > ul > li.on").length;
        var current_page_count = $("#j_list_card > ul > li.salable").length;
        if (count < current_page_count || count === 0) {
            $(".w-Checkbox[name=select-all] span").removeClass("on");
            $(".w-Checkbox[name=select-all]").attr({
                value: ""
            })
        } else {
            $(".w-Checkbox[name=select-all] span").addClass("on");
            $(".w-Checkbox[name=select-all]").attr({
                value: "selectall"
            })
        }
    };
    var update_overpage = function(no_render) {
        var sorted_selected = get_sorted_selected();
        var total_count = visible_backpack_count;
        $("#j_overpage-handler").find(".selected-count").text(sorted_selected.length);
        $("#j_overpage-handler").find(".total-count").text(visible_backpack_count);
        var total_price = 0;
        var infos = {};
        sorted_selected.forEach(function(backpackid) {
            var goods_info = goods_infos[items[backpackid].goods_id];
            var asset_info = items[backpackid].asset_info;
            total_price += parseFloat(goods_info.steam_price);
            infos[backpackid] = {
                appid: goods_info.appid,
                name: goods_info.name,
                assetid: asset_info.assetid,
                contextid: asset_info.contextid,
                classid: asset_info.classid,
                instanceid: asset_info.instanceid,
                icon_url: asset_info.info.icon_url || goods_info.icon_url
            }
        });
        if (!no_render || sorted_selected.length == 0) {
            $("#j_overpagetip").html(template_render("overpagetip_template", {
                selected: sorted_selected,
                total_price: total_price,
                infos: infos
            }))
        } else {
            $("#j_overpagetip").find(".f_Strong").html(formatPriceNormalCustom(total_price, undefined, "USD"));
            $("#j_overpagetip").find("#selected-count").text(sorted_selected.length)
        }
    };
    var update_counts = function() {
        var html = template_render("brief_info_pat", {
            backpack_count: backpack_count,
            visible_backpack_count: visible_backpack_count,
            backpack_limit: backpack_limit,
            total_amount: total_amount
        });
        $(".brief-info").html(html)
    };
    var check_price_value = sellingPricing().check_price_value;
    var update_fee = function() {
        clearTimeout(update_fee_timer);
        jQuery.xhrPool.abort("/api/market/batch/fee");
        update_fee_timer = setTimeout(function() {
            var prices = [];
            var indices = [];
            var total_price = 0;
            var total_fee = 0;
            for (var i = 0; i < assets.length; i++) {
                if (!assets[i])
                    continue;
                if (assets[i].price > 0) {
                    if (check_price_value(assets[i].price, false) == false) {
                        return
                    }
                    if (!assets[i].has_market_min_price) {
                        prices.push(assets[i].price);
                        indices.push(i);
                        total_price += assets[i].price
                    } else {
                        total_price += assets[i].income
                    }
                }
            }
            if (prices.length < 1) {
                $("#j_popup_selling_preview span.sale_fee").html(formatPriceYuan(total_fee));
                $("#j_popup_selling_preview span.real_income").html(formatPriceYuan(total_price - total_fee));
                $("#j_popup_selling_preview span.real_income_custom").html(formatPriceNormalCustom(total_price - total_fee));
                return
            }
            $("#j_popup_selling_preview .confirm").addClass("i_Btn_disabled");
            sendRequest("/api/market/batch/fee", {
                data: {
                    game: game,
                    prices: prices.join(",")
                },
                dataType: "json",
                method: "GET",
                showLoading: false,
                success: function(data) {
                    if (data.code == "OK") {
                        $("#j_popup_selling_preview .confirm").removeClass("i_Btn_disabled");
                        total_fee += parseFloat(data.data.total_fee);
                        $("#j_popup_selling_preview span.sale_fee").html(formatPriceYuan(total_fee));
                        $("#j_popup_selling_preview span.real_income").html(formatPriceYuan(total_price - parseFloat(total_fee)));
                        $("#j_popup_selling_preview span.real_income_custom").html(formatPriceNormalCustom(total_price - parseFloat(total_fee)));
                        $("#j_popup_selling_preview input[name=income]").each(function() {
                            var index = $(this).data("index") - 1;
                            if (indices.indexOf(index) != -1) {
                                if (!$(this).is(":focus")) {
                                    assets[index].income = assets[index].price - parseFloat(data.data.fees[indices.indexOf(index)]);
                                    $(this).val(assets[index].income.toFixed(2));
                                    $(this).parents("tr").find(".sell-income-custom").text(formatPriceNormalCustom(assets[index].income, true));
                                    $(this).removeClass("i_Text_error")
                                }
                            }
                        })
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                },
                error: function(resp) {
                    if (resp.statusText != "abort") {
                        Buff.toast(i18n("acquisition_fee_failed_please_try"))
                    }
                }
            })
        }, 500)
    };
    var update_items = function(dont_refresh_amount) {
        $("#backpack_list").showLoading();
        var query = getParams();
        query.page_num = getParamsFromHash().page_num || 1;
        sendRequest("/api/market/backpack", {
            method: "GET",
            data: query,
            showLoading: false,
            ignoreCode: ["Steam Binding Required"],
            success: function(data) {
                if (data.code == "OK") {
                    updateView(data.data);
                    if (data.notice) {
                        var tip = "";
                        $(".market-tip.backpack-tip").show();
                        if (data.notice.extra) {
                            tip = '<span class="j_tips_handler" data-title=" " data-content="' + data.notice.extra + '"><i class="icon icon_qa"></i></span>'
                        }
                        $(".market-tip.backpack-tip").html("<div><p>" + data.notice.text + tip + "</p></div>");
                        $(".market-tip.backpack-tip").addClass("market-tip_" + data.notice.type)
                    } else {
                        $(".market-tip.backpack-tip").show()
                    }
                }
            },
            complete: function() {
                $("#backpack_list").removeLoading()
            }
        });
        if (!dont_refresh_amount) {
            update_total_amount()
        }
    };
    var update_selected_style = function() {
        $("#j_list_card > ul > li.salable").each(function() {
            if (selected[$(this).data("backpackid")]) {
                $(this).addClass("on")
            } else {
                $(this).removeClass("on")
            }
        })
    };
    var updateView = function(data) {
        var html = template_render("backpack_list_pat", data);
        $("#backpack_list").html(html);
        data.items.forEach(function(item) {
            items[item.id] = item
        });
        goods_infos = $.extend(goods_infos, data.goods_infos);
        backpack_count = data.backpack_count;
        backpack_limit = data.backpack_limit;
        visible_backpack_count = data.total_count;
        update_counts();
        update_selected_style();
        update_select_all_state();
        update_overpage();
        renderPagination({
            total_count: data.total_count,
            page_size: data.page_size,
            page_num: data.page_num,
            show_size_select: false,
            onPageClick: function(page, event) {
                event.preventDefault();
                updateHash("page_num", page);
                update_items(true)
            }
        })
    };
    var update_total_amount = function() {};
    var check_trade_state = function() {
        sendRequest("/account/api/user/info", {
            method: "GET",
            dataType: "json",
            showLoading: false,
            timeout: 15e3,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error);
                    return
                } else if ([0, 1].indexOf(data.data.trade_url_state) == -1) {
                    $("#trade_state_tip").show();
                    $("#withdraw").addClass("i_Btn_disabled")
                }
            }
        })
    };
    var init = function() {
        update_items();
        $(document).on("click", "#recheck_trade_state", function() {
            sendRequest("/api/market/steam/trade_url_state/refresh", {
                method: "POST",
                dataType: "json",
                timeout: 15e3,
                success: function(data) {
                    if (data.code == "OK") {
                        if ([0, 1].indexOf(data.data.trade_url_state) > -1) {
                            Buff.toast(i18n("it_detects_your_steam_account"));
                            $("#trade_state_tip").hide();
                            $("#withdraw").removeClass("i_Btn_disabled")
                        } else if (data.data.trade_url_state == 2) {
                            Buff.toast(i18n("it_detects_your_steam_account"), {
                                type: "error"
                            })
                        }
                    } else {
                        Buff.toast(i18n("detection_failed_please_try_again"))
                    }
                }
            })
        });
        $("#withdraw").click(function() {
            if ($(this).hasClass("i_Btn_disabled"))
                return;
            Buff.guide({
                title: i18n("retrieve_the_process_description"),
                rememberDismiss: "backpack_withdraw",
                hideClose: false,
                onConfirm: doWithdraw,
                content: '<img style="width:100%;margin-top: 20px;" src="/static/images/first_fetch_from_backpack.png"/><div class="guide-strong"><a href="/help#how_to_fetch_cosmetics" target="_blank" class="f_14px">查看取回饰品详细教程</a></div>'
            })
        });
        var doWithdraw = function() {
            var backpack_ids = get_sorted_selected();
            if (backpack_ids.length == 0) {
                Buff.toast(i18n("select_to_retrieve_the_goods"));
                return
            }
            sendRequest("/api/market/backpack/withdraw", {
                data: {
                    game: game,
                    backpack_ids: backpack_ids
                },
                showLoading: false,
                method: "POST",
                dataType: "json",
                success: function(data) {
                    if (data.code == "OK") {
                        for (var i = 0; i < data.data.length; i++) {
                            bot_trades[data.data[i].id] = data.data[i]
                        }
                        selected = {};
                        update_items();
                        render_bot()
                    } else if (data.code == "Steam Trade URL Binding Required") {
                        Buff.alert({
                            title: i18n("prompt"),
                            message: i18n("unbound_steam_trading_link_whether"),
                            success: function() {
                                window.open("/user-center/profile", "_blank")
                            },
                            cancel: function() {
                                Buff.toast(i18n("retrieval_failure"))
                            }
                        })
                    } else if (data.code == "Steam Trade Limit") {
                        Buff.alert({
                            title: i18n("prompt"),
                            message: i18n("your_current_steam_account_cant"),
                            success: function() {
                                window.open("/help#before_trade", "_blank")
                            },
                            cancel: function() {
                                Buff.toast(i18n("retrieval_failure"))
                            }
                        })
                    } else if (data.code == "Steam Trade URL Failure") {
                        Buff.alert({
                            title: i18n("prompt"),
                            message: i18n("your_steam_trade_url_invalid"),
                            success: function() {
                                window.open("/user-center/profile", "_blank")
                            },
                            cancel: function() {
                                Buff.toast(i18n("retrieval_failure"))
                            }
                        })
                    } else {
                        Buff.toast(data.error)
                    }
                }
            })
        };
        update_bot({
            polling: true,
            onStateChange: function(_old, _new) {
                update_items()
            }
        });
        $(document).on("click", "#j_list_card > ul > li.salable", function() {
            $(this).toggleClass("on");
            $(this).trigger("change");
            update_select_all_state();
            update_overpage()
        });
        $(document).on("change", "#j_list_card > ul > li.salable", function() {
            var backpackid = $(this).data("backpackid");
            if ($(this).hasClass("on")) {
                if (Object.keys(selected).length >= 200 && !selected[backpackid]) {
                    Buff.toast(i18n("select_up_to_200_pieces"));
                    $(this).toggleClass("on");
                    return
                }
                selected[backpackid] = Date.now()
            } else {
                delete selected[backpackid]
            }
        });
        $(".w-Checkbox[name=select-all]").change(function() {
            var value = $(this).attr("value");
            if (value == "selectall") {
                $("#j_list_card > ul > li.salable").addClass("on");
                if ($("#j_list_card > ul > li.salable").length < 1) {
                    Buff.toast(i18n("the_current_page_is_no"))
                }
            } else {
                $("#j_list_card > ul > li.salable").removeClass("on")
            }
            $("#j_list_card > ul > li.salable").trigger("change");
            update_select_all_state();
            update_overpage()
        });
        $("#confirm-shelve").click(function() {
            if ($("#j_popup_sellauto .w-Checkbox").attr("value") === "dontshow") {
                localStorage.setItem("remember_dismiss_auto_sell", "1")
            }
            doPreview()
        });
        $("#shelve").click(function() {
            if (localStorage.getItem("remember_dismiss_auto_sell")) {
                doPreview();
                return
            }
            Popup.show("j_popup_sellauto")
        });
        var doPreview = function() {
            var _assets = [];
            get_sorted_selected().forEach(function(backpackid) {
                var item = items[backpackid];
                _assets.push({
                    game: item.game,
                    market_hash_name: goods_infos[item.goods_id].market_hash_name,
                    contextid: item.asset_info.contextid,
                    assetid: item.asset_info.assetid,
                    classid: item.asset_info.classid,
                    instanceid: item.asset_info.instanceid,
                    goods_id: item.goods_id,
                    price: "",
                    income: "",
                    has_market_min_price: false
                });
                asset_info[item.asset_info.assetid] = goods_infos[item.goods_id];
                asset_backpackid[item.asset_info.assetid] = backpackid
            });
            assets = _assets;
            if (assets.length < 1) {
                Buff.toast(i18n("please_choose_to_be_on"));
                return
            }
            sendRequest("/market/sell_order/preview/auto", {
                data: {
                    game: game,
                    assets: assets
                },
                dataType: "json",
                method: "POST",
                success: function(data) {
                    if (data.code == "OK") {
                        $("#popup-container").html(data.data);
                        initCustomCurrency($("#j_popup_selling_preview"));
                        Popup.show("j_popup_selling_preview");
                        Buff.pricePatten("input[name=price]");
                        Buff.pricePatten("input[name=income]")
                    } else {
                        Buff.alert({
                            type: "error",
                            title: i18n("on_frame_failure"),
                            message: data.error,
                            hideCancel: true
                        })
                    }
                }
            })
        };
        var update_assets_price = function() {
            $("#j_popup_selling_preview tr.assets-item input[name=price]").each(function() {
                var index = $(this).data("index") - 1;
                var price = parseFloat($(this).val());
                if (isNaN(price) || $(this).val().length == 0) {
                    assets[index].price = ""
                } else {
                    assets[index].price = price
                }
            });
            $("#j_popup_selling_preview tr.assets-item input[name=income]").each(function() {
                var index = $(this).data("index") - 1;
                var income = parseFloat($(this).val());
                if (isNaN(income) || $(this).val().length == 0) {
                    assets[index].income = ""
                } else {
                    assets[index].income = income
                }
            })
        };
        $(document).on("change", ".w-Checkbox[name=combine]", function() {
            var value = $(this).attr("value");
            if (value == "combine") {
                var group_key_data = $("#j_popup_selling_preview").data("group-key");
                for (var group_key in group_key_data) {
                    if (group_key_data[group_key].assetids.length > 1) {
                        $("#j_popup_selling_preview tr.group_key_" + group_key + ":not(:first)").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + ":first .name-cont p.num").remove();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + ":first .name-cont").append('<p class="num c_Gray" style="font-size: 13px;"> ×' + group_key_data[group_key].assetids.length + "</p>");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " input").val("");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .sell-price-custom").html("");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .sell-income-custom").html("");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .pic-cont .item-count").show();
                        $("#j_popup_selling_preview tr.group_key_" + group_key).next(".des_row").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " td").css("border-bottom", "1px solid #E9E9E9");
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .edit_order_desc a").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .paint-wear").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .csgo_sticker_inline").hide();
                        $("#j_popup_selling_preview tr.group_key_" + group_key + " .group_key_notice").show()
                    }
                }
                update_assets_price();
                update_fee()
            } else {
                $("#j_popup_selling_preview tr.assets-item").show();
                $("#j_popup_selling_preview tr.assets-item .edit_order_desc a").show();
                $("#j_popup_selling_preview tr.assets-item .paint-wear").show();
                $("#j_popup_selling_preview tr.assets-item .csgo_sticker_inline").show();
                $("#j_popup_selling_preview tr.assets-item.has_des").next().show();
                $("#j_popup_selling_preview tr.assets-item.has_des td").css("border-bottom", "0");
                $("#j_popup_selling_preview tr.assets-item .name-cont p.num").remove();
                $("#j_popup_selling_preview tr.assets-item .pic-cont .item-count").hide();
                $("#j_popup_selling_preview tr.assets-item .group_key_notice").hide()
            }
        });
        $(document).on("input", "#j_popup_selling_preview input[name=price], #j_popup_trans input[name=price], #j_popup_private input[name=price]", function() {
            var index = $(this).data("index") - 1;
            var input_price = $(this).val();
            var input_income = $(this).parents("tr").find("input[name=income]").val();
            var price = parseFloat(input_price);
            var income = parseFloat(input_income);
            var market_min_price = parseFloat($(this).data("market-min-price"));
            if (market_min_price > 0 && price < market_min_price) {
                price = market_min_price
            }
            if (check_price_value($(this).val())) {
                $(this).removeClass("i_Text_error")
            } else {
                $(this).addClass("i_Text_error")
            }
            assets[index].price = price;
            assets[index].income = income;
            assets[index].has_market_min_price = market_min_price > 0;
            var value = $(".w-Checkbox[name=combine]").attr("value");
            if (value == "combine") {
                var group_key_data = $("#j_popup_selling_preview").data("group-key");
                var group_key = $(this).data("group-key");
                var assetids = group_key_data[group_key].assetids;
                for (var i = 0; i < assets.length; i++) {
                    if (assetids.indexOf(assets[i].assetid) > -1) {
                        assets[i].price = assets[index].price;
                        assets[i].income = assets[index].income;
                        assets[i].has_market_min_price = assets[index].has_market_min_price
                    }
                }
                $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=price]").val(input_price);
                $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=income]").val(input_income);
                $("#j_popup_selling_preview tr.group_key_" + group_key + " .sell-price-custom").html(price ? formatPriceNormalCustom(price, true) : "");
                $("#j_popup_selling_preview tr.group_key_" + group_key + " .sell-price-income").html(income ? formatPriceNormalCustom(income, true) : "");
                if ($(this).hasClass("i_Text_error")) {
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=price]").addClass("i_Text_error");
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=income]").addClass("i_Text_error")
                } else {
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=price]").removeClass("i_Text_error");
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " input[name=income]").removeClass("i_Text_error");
                    $("#j_popup_selling_preview tr.group_key_" + group_key + " .cannot-quick-pricing").remove()
                }
            }
            if (price) {
                $(this).parents("tr").find(".sell-price-custom").html(formatPriceNormalCustom(price, true))
            } else {
                $(this).parents("tr").find(".sell-price-custom").html("")
            }
            update_fee()
        });
        $(document).on("change", "#j_popup_selling_preview input[name=price], #j_popup_trans input[name=price], #j_popup_private input[name=price]", function() {
            if (check_price_value($(this).val(), true)) {
                update_fee()
            }
        });
        var selling_pricing = sellingPricing();
        $(document).on("input", "#j_popup_selling_preview input[name=income]", function() {
            selling_pricing.get_price_from_income($(this).parents("tr"));
            var income = $(this).val();
            if (income) {
                $(this).parents("tr").find(".sell-income-custom").html(formatPriceNormalCustom(income, true))
            } else {
                $(this).parents("tr").find(".sell-income-custom").html("")
            }
        });
        $(document).on("change", "#j_popup_selling_preview input[name=income]", function() {
            if (check_price_value($(this).val(), true)) {
                selling_pricing.get_price_from_income($(this).parents("tr"))
            }
        });
        $(document).on("click", "#j_popup_selling_preview #quick-pricing", function() {
            selling_pricing.quick_pricing($("#j_popup_selling_preview"));
            update_fee()
        });
        $(document).on("click", "#j_popup_selling_preview .confirm:not(.i_Btn_disabled)", function() {
            for (var i = 0; i < assets.length; i++) {
                if (check_price_value(assets[i].price, true) == false) {
                    return
                }
            }
            selling_pricing.find_unusual_price($("#j_popup_selling_preview"), function() {
                sendRequest("/api/market/sell_order/create/auto", {
                    data: {
                        game: game,
                        assets: assets
                    },
                    method: "POST",
                    timeout: Math.max(5e3, 1e3 * assets.length),
                    success: function(data) {
                        if (data.code == "OK") {
                            var msg = "";
                            var success = 0;
                            var failures = [];
                            for (var i = 0; i < assets.length; i++) {
                                var assetid = assets[i].assetid;
                                var result = data.data[assetid];
                                if (result == "OK") {
                                    success += 1;
                                    delete selected[asset_backpackid[assetid]]
                                } else {
                                    failures.push({
                                        asset: assets[i],
                                        reason: result,
                                        info: asset_info[assetid]
                                    })
                                }
                            }
                            if (failures.length > 0) {
                                Popup.hide();
                                var html = template_render("result_pat", {
                                    failures: failures,
                                    success: success
                                });
                                $("#popup-container").html(html);
                                Popup.show("j_popup_charge-result")
                            } else {
                                Buff.toast(i18n("items_on_the_shelves_successful"), {
                                    type: "success"
                                });
                                Popup.hide()
                            }
                            update_items()
                        } else if (data.code == "Invalid Argument" && data.error.indexOf("price") > -1) {
                            Buff.toast(i18n("there_goods_is_not_input"), {
                                type: "error"
                            })
                        } else {
                            Buff.toast(data.error || data.code, {
                                type: "warning"
                            })
                        }
                    }
                })
            })
        });
        $(document).on("click", ".edit_order_desc a", function() {
            var assetid = $(this).data("assetid");
            Popup.show("j_pupup_add_desc");
            var content = $("#asset_" + assetid).next().find(".desc_content").text();
            $("#j_pupup_add_desc .addDesCount").text(content.length + "/40");
            $("#j_pupup_add_desc .addDesWrapper textarea").val(content);
            $("#j_pupup_add_desc .i_Btn_main").data("assetid", assetid)
        });
        $(document).on("click", "#j_pupup_add_desc .i_Btn_main", function() {
            var assetid = $(this).data("assetid");
            var content = $("#j_pupup_add_desc .addDesWrapper textarea").val();
            if (content.length > 40) {
                Buff.toast(i18n("the_content_of_the_input"))
            } else {
                $("#asset_" + assetid).next().find(".desc_content").text(content);
                for (var i = 0; i < assets.length; i++) {
                    if (assets[i].assetid == assetid) {
                        assets[i].desc = content
                    }
                }
                if (content.length > 0) {
                    $("#asset_" + assetid).next().show();
                    $("#asset_" + assetid).addClass("has_des");
                    $("#asset_" + assetid + " .edit_order_desc a").text(i18n("edit_the_description"))
                } else {
                    $("#asset_" + assetid).next().hide();
                    $("#asset_" + assetid).removeClass("has_des");
                    $("#asset_" + assetid + " .edit_order_desc a").text(i18n("add_a_description"))
                }
                Popup.hide()
            }
        });
        $(document).on("input", "#j_pupup_add_desc .addDesWrapper textarea", function() {
            $("#j_pupup_add_desc .addDesCount").text($(this).val().length + "/40")
        });
        $("#bundle-shelve").click(function() {
            if (!$(this).data("has-perm")) {
                Buff.toast(i18n("packaged_transaction_within_the_test"), {
                    type: "warning"
                });
                return
            }
            var sorted_selected = get_sorted_selected();
            if (sorted_selected.length < 2) {
                Buff.toast(i18n("require_minimal_packaging_of_two"));
                return
            }
            assets = [{
                price: 0
            }];
            var sum_price = 0;
            for (var i = 0; i < sorted_selected.length; i++) {
                sum_price += parseFloat(goods_infos[items[sorted_selected[i]].goods_id].steam_price_cny)
            }
            var html = template_render("bundle_pat", {
                selected: sorted_selected,
                items: items,
                goods_infos: goods_infos,
                sum_price: sum_price
            });
            $("#popup-container").html(html);
            Popup.show("j_popup_trans")
        });
        $(document).on("click", "#j_popup_trans .confirm", function() {
            var price = $("#j_popup_trans input[name=price]").val();
            var description = $("#j_popup_trans input[name=description]").val();
            var images = [];
            $("#j_popup_trans #uploaded-pics img.success").each(function(idx, ele) {
                images.push($(ele).data("src"))
            });
            if (!price || !price.length) {
                Buff.toast(i18n("please_enter_pricing"), {
                    type: "error"
                });
                return
            }
            if ($(".upload-item:not(.success)").length > 0) {
                Buff.toast(i18n("a_picture_is_not_uploaded"), {
                    type: "error"
                });
                return
            }
            if (check_price_value(price, true) == false) {
                return
            }
            sendRequest("/api/market/sell_order/create/bundle", {
                method: "POST",
                dataType: "json",
                data: {
                    game: g.game,
                    backpack_ids: get_sorted_selected(),
                    price: price,
                    description: description,
                    images: images
                },
                success: function(data) {
                    if (data.code !== "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    } else {
                        Buff.toast(i18n("create_a_package_of_trading"), {
                            type: "success"
                        });
                        selected = {};
                        update_items();
                        Popup.hide()
                    }
                }
            })
        });
        $("#private-shelve").click(function() {
            if (!$(this).data("has-perm")) {
                Buff.toast(i18n("private_transaction_within_the_test"), {
                    type: "warning"
                });
                return
            }
            var sorted_selected = get_sorted_selected();
            if (sorted_selected.length < 1) {
                Buff.toast(i18n("please_choose_to_be_a"));
                return
            }
            assets = [{
                price: 0
            }];
            var sum_price = 0;
            for (var i = 0; i < sorted_selected.length; i++) {
                sum_price += parseFloat(goods_infos[items[sorted_selected[i]].goods_id].steam_price_cny)
            }
            var html = template_render("bundle_pat", {
                selected: sorted_selected,
                items: items,
                goods_infos: goods_infos,
                sum_price: sum_price,
                isPrivate: true
            });
            $("#popup-container").html(html);
            Popup.show("j_popup_private")
        });
        $(document).on("click", "#j_popup_private .confirm", function() {
            var price = $("#j_popup_private input[name=price]").val();
            if (!price || !price.length) {
                Buff.toast(i18n("please_enter_pricing"), {
                    type: "error"
                });
                return
            }
            if (check_price_value(price, true) == false) {
                return
            }
            if ($(".upload-item:not(.success)").length > 0) {
                Buff.toast(i18n("a_picture_is_not_uploaded"), {
                    type: "error"
                });
                return
            }
            var images = [];
            $("#j_popup_private #uploaded-pics img.success").each(function(idx, ele) {
                images.push($(ele).data("src"))
            });
            Popup.hide();
            var send_authcode = function(callback) {
                sendRequest("/api/market/sell_order/create/private/send_authcode", {
                    method: "POST",
                    dataType: "json",
                    showLoading: false,
                    success: function() {
                        if (callback) {
                            callback()
                        }
                    }
                })
            };
            bindCard.show_authcode_popup({
                send_authcode_function: send_authcode,
                verify_authcode_function: function(authcode, callback) {
                    sendRequest("/api/market/sell_order/create/private", {
                        method: "POST",
                        data: {
                            game: g.game,
                            backpack_ids: get_sorted_selected(),
                            price: price,
                            authcode: authcode,
                            images: images
                        },
                        success: function(data) {
                            if (data.code !== "OK") {
                                Buff.toast(data.error, {
                                    type: "error"
                                })
                            } else {
                                callback();
                                $("#j_popup_private-link").find(".i_Text").text(data.data.link);
                                $("#j_popup_private-link").find(".i_Btn_main").click(function() {
                                    setClipboard(data.data.link);
                                    Buff.toast(i18n("replicated"), {
                                        type: "success"
                                    })
                                });
                                Popup.show("j_popup_private-link");
                                selected = {};
                                update_items()
                            }
                        }
                    })
                },
                mobile: $("#mobile").text(),
                authcode_length: 4,
                popup_id: "j_popup_private-check"
            });
            send_authcode()
        });
        $(document).on("click", ".overpage-del", function() {
            delete selected[$(this).data("id")];
            $(this).parent().remove();
            update_overpage(true);
            update_selected_style();
            update_select_all_state()
        });
        gallery.init()
    };
    return {
        init: init
    }
};
var storeInfo = function() {
    var init = function() {
        $("body").on("focus", ".timepicker input", function() {
            if ($(this).parent().hasClass("disabled")) {
                $(this).blur();
                return false
            } else {
                var index = $(".timepicker input").index(this);
                $(".timepicker-drop").eq(index).show()
            }
        }).on("blur", ".timepicker input", function() {
            var _this = this;
            setTimeout(function() {
                var index = $(".timepicker input").index(_this);
                $(".timepicker-drop").eq(index).hide()
            }, 200)
        }).on("keypress", ".timepicker input", function() {
            return false
        }).on("click", ".timepicker-drop li", function() {
            $(this).addClass("on").siblings().removeClass("on");
            var inputID = $(this).parent().attr("data-for");
            $("#" + inputID).val($(this).html())
        }).on("change", "#j_autoClose", function() {
            if ($(this).attr("value") != "") {
                $("#j_timepicker").removeClass("disabled")
            } else {
                $("#j_timepicker").addClass("disabled")
            }
        }).on("click", "#set_store_name, #modify_store_name", function() {
            $("#store_name").find(".store_name_tab1").hide();
            $("#store_name").find(".store_name_tab2").show();
            $("#store_name_input").val($("span.store_name_span").attr("pre_text"))
        }).on("click", "#change_store_name_cancel", function() {
            $("#store_name").find(".store_name_tab1").show();
            $("#store_name").find(".store_name_tab2").hide()
        }).on("click", "#change_store_name_confirm", function() {
            var name = $("#store_name_input").val();
            if (!name) {
                Buff.toast(i18n("please_input_store_name"));
                return
            }
            if ($("span.store_name_span").attr("pre_text") == name) {
                Buff.toast(i18n("have_not_modify_store_name"));
                return
            }
            var change_store_name = function(cdkey_id) {
                sendRequest("/api/market/user_store/change_name", {
                    method: "POST",
                    data: {
                        name: name,
                        cdkey_id: cdkey_id
                    },
                    success: function(data) {
                        if (data.code === "OK") {
                            $("#store_name").find(".store_name_tab1").show();
                            $("#store_name").find(".store_name_tab2").hide();
                            $("#store_name_input").val("");
                            $("span.store_name_span").text(name);
                            $("span.store_name_span").attr("has_set", name);
                            $("span.store_name_span").attr("pre_text", name);
                            Buff.toast(i18n("set_success"), {
                                type: "success"
                            })
                        } else {
                            Buff.toast(data.error, {
                                type: "error"
                            })
                        }
                    }
                })
            };
            if (!$("span.store_name_span").attr("has_set")) {
                change_store_name();
                return
            }
            Buff.alert({
                title: i18n("prompt"),
                message: i18n("determine_use_store_name_coupon"),
                success: function() {
                    sendRequest("/api/activity/coupon/my/", {
                        method: "GET",
                        data: {
                            state: "unuse",
                            coupon_type: "store_rename"
                        },
                        success: function(data) {
                            if (data.data && data.data.items.length == 0) {
                                Buff.toast(i18n("please_exchange_store_name_coupon_at_app"));
                                return
                            }
                            change_store_name(data.data.items[0].id)
                        }
                    })
                }
            })
        });
        $("#j_popup_shop a.confirm").click(function() {
            var auto_offline = $("#j_autoClose").attr("value") || "0";
            var auto_offline_hour = $("#j_input-hour").val();
            var auto_offline_minute = $("#j_input-minute").val();
            if (auto_offline !== "0" && (!auto_offline_hour || !auto_offline_minute)) {
                Buff.toast(i18n("please_enter_the_auto_logoff"));
                return
            }
            sendRequest("/api/market/user_store/change_state", {
                method: "POST",
                data: {
                    state: $("#j_storeState").attr("value"),
                    auto_offline: auto_offline,
                    auto_offline_hour: auto_offline_hour,
                    auto_offline_minute: auto_offline_minute
                },
                success: function(data) {
                    if (data.code === "OK") {
                        Popup.hide();
                        Buff.toast(i18n("set_success"), {
                            type: "success"
                        });
                        if ($("#j_storeState").attr("value") == 0) {
                            $(".has-store, .icon-store").removeClass("store-offline").addClass("store-online");
                            $(".c_Yellow.offline_tips").hide();
                            $(".c_Yellow.deliver_tips").show()
                        } else {
                            $(".has-store, .icon-store").removeClass("store-online").addClass("store-offline")
                        }
                    } else {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    }
                }
            })
        });
        $("#store_name").find(".store_name_tab1").show();
        $("#store_name").find(".store_name_tab2").hide()
    };
    return {
        init: init
    }
};
var buyingToCreate = function() {
    var game = g.game;
    var loadGoods = function() {
        $("#j_list_card").showLoading();
        var query = getParams();
        query.page_size = 70;
        sendRequest("/api/market/goods/all", {
            data: query,
            method: "GET",
            showLoading: false,
            success: function(data) {
                var html = template_render("goods_list_pat", data.data);
                $("#j_list_card").html(html);
                renderPagination({
                    total_count: data.data.total_count,
                    page_size: data.data.page_size,
                    page_num: data.data.page_num,
                    show_size_select: false,
                    size_selects: [70, 140, 210],
                    onPageClick: function(page, event) {
                        event.preventDefault();
                        updateSearchPage("page_num", page);
                        $("html,body").scrollTop(0)
                    }
                })
            },
            complete: function() {
                $("#j_list_card").removeLoading()
            }
        })
    };
    var init = function() {
        loadGoods();
        $(document).on("click", "li.salable a.goods_link", function(e) {
            e.stopPropagation()
        })
    };
    return {
        init: init
    }
};
var buyingSupplied = function(user_id) {
    var game = g.game;
    var init = function() {
        $(".with-gallery").click(function() {
            var index = $(".with-gallery").index(this);
            galleryToggled(index)
        });
        $(".j_gallery_handler").click(function() {
            var index = $(".j_gallery_handler").index(this);
            galleryToggled(index)
        });
        var galleryToggled = function(index) {
            var that = $(".j_gallery_handler").eq(index);
            var $container = $(".tr_gallery").eq(index).find("td");
            if ($container.html())
                return;
            $container.find("td").showLoading();
            sendRequest("/api/market/buy_order/supplied/bill_orders", {
                data: {
                    game: game,
                    buy_order_id: $(that).data("orderid")
                },
                method: "GET",
                showLoading: false,
                success: function(data) {
                    data.data.goods = {
                        icon_url: $(that).data("goods-icon-url"),
                        rarity: $(that).data("goods-rarity"),
                        name: $(that).data("goods-name")
                    };
                    var html = template_render("supplied_bill_orders_pat", data.data);
                    $container.html(html)
                },
                error: function(data) {
                    Buff.toast(data.error, {
                        type: "error"
                    });
                    $container.removeLoading()
                }
            })
        }
    };
    return {
        init: init
    }
};
var userStore = function(store_user_id, current_user_id, current_game) {
    var showBillOrders = function() {
        $("#recent-deal-container").showLoading();
        sendRequest("/api/market/shop/" + store_user_id + "/bill_order", {
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    data.data = {
                        items: []
                    }
                }
                $("#recent-deal-container").html(template_render("recent_deal_template", data.data))
            }
        })
    };
    var showFeatured = function() {
        $("#recommend-container").showLoading();
        sendRequest("/api/market/shop/" + store_user_id + "/featured", {
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    data.data = {
                        items: []
                    }
                }
                $("#recommend-container").html(template_render("recommend_template", data.data));
                if (data.data.items.length) {
                    $(".featured").show();
                    setShopRecommend()
                }
            }
        })
    };
    var showSellOrder = function() {
        var hash = getParamsFromHash();
        $("#orders-container").showLoading();
        sendRequest("/api/market/shop/" + store_user_id + "/sell_order", {
            data: hash,
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    data.data = {
                        items: []
                    }
                }
                $("#orders-container").html(template_render("sell_order_template", data.data));
                if (data.data.items) {
                    renderPagination({
                        total_count: data.data.total_count,
                        page_size: data.data.page_size,
                        page_num: data.data.page_num,
                        show_size_select: false,
                        onPageClick: function(page, event) {
                            event.preventDefault();
                            updateHash("page_num", page);
                            window.scrollTo(0, 0)
                        }
                    })
                }
            }
        })
    };
    var showBuyOrder = function() {
        var hash = getParamsFromHash();
        $("#orders-container").showLoading();
        sendRequest("/api/market/shop/" + store_user_id + "/buy_order", {
            data: hash,
            method: "GET",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    data.data = {
                        items: []
                    }
                }
                $("#orders-container").html(template_render("buy_order_template", data.data));
                if (data.data.items) {
                    renderPagination({
                        total_count: data.data.total_count,
                        page_size: data.data.page_size,
                        page_num: data.data.page_num,
                        show_size_select: false,
                        onPageClick: function(page, event) {
                            event.preventDefault();
                            updateHash("page_num", page);
                            window.scrollTo(0, 0)
                        }
                    })
                }
            }
        })
    };
    var updateUIState = function() {
        var hash = getParamsFromHash();
        $(".store-game-selector").parent().removeClass("on");
        $(".store-game-selector[data-game=" + hash.game + "]").parent().addClass("on");
        $("#item-filters-container").html(template_render(hash.game + "_filters_template", {}));
        Buff.initSelect(".w-Select");
        Buff.initSelectMulti(".w-Select-Multi");
        $("#tab-selector > li").removeClass("on");
        $("#tab-selector > li[data-tab=" + hash.tab + "]").addClass("on");
        if (hash.tab == "buying") {
            showBuyOrder()
        } else {
            showSellOrder()
        }
    };
    var init = function() {
        normalBuy(current_user_id).init();
        supplySell(current_user_id).init();
        gameNavigator.setKeepParams(["user_id"]);
        $("#j_mw").change(function() {
            $(".shop-info-wrap").hide();
            $(".shop-info-wrap." + $(this).attr("value")).show()
        });
        showBillOrders();
        showFeatured();
        var hash = getParamsFromHash();
        if (!hash.tab) {
            hash.tab = "selling"
        }
        if (!hash.game) {
            hash.game = current_game
        }
        updateHashData(hash);
        updateUIState();
        $("#tab-selector > li").click(function() {
            if ($(this).hasClass("on"))
                return;
            updateHashData({
                tab: $(this).data("tab"),
                page_num: 1
            })
        });
        $(".store-game-selector").click(function() {
            if ($(this).parent().hasClass("on"))
                return;
            var game = $(this).data("game");
            var params = getParamsFromHash();
            for (key in params) {
                if (key !== "tab" && key !== "sort_by" && key !== "mode") {
                    params[key] = ""
                }
            }
            params.game = game;
            updateHashData(params)
        });
        $(window).on("hashchange", function() {
            updateUIState()
        });
        window.updateSearch = function(key, value) {
            updateHash(key, value);
            updateHash("page_num", 1)
        }
        ;
        window.updateSearchData = function(data) {
            data.page_num = 1;
            updateHashData(data)
        }
    };
    return {
        init: init
    }
};
var bundleList = function() {
    var game = g.game;
    var _MAX_PRICE = BuffConfig.MAX_SELL_PRICE;
    var _MIN_PRICE = BuffConfig.MIN_PRICE;
    var should_update_fee = false;
    var assets = [];
    var check_price_value = function(price, toast) {
        if (typeof price == "string" && price.length == 0 || typeof price == "object" || isNaN(price)) {
            if (toast) {
                Buff.toast(i18n("there_goods_is_not_input"), {
                    type: "error"
                })
            }
            return false
        }
        price = parseFloat(price);
        if (price < _MIN_PRICE) {
            if (toast) {
                Buff.toast(i18n("price_must_be_greater_than") + _MIN_PRICE)
            }
            return false
        }
        return true
    };
    var update_fee = function() {
        if (should_update_fee == true) {
            should_update_fee = false
        } else {
            return
        }
        var prices = [];
        var total_price = 0;
        for (var i = 0; i < assets.length; i++) {
            if (!assets[i])
                continue;
            if (assets[i].price > 0) {
                if (check_price_value(assets[i].price, false) == false) {
                    return
                }
                prices.push(assets[i].price);
                total_price += assets[i].price
            }
        }
        if (prices.length < 1) {
            $("span.sale_fee").html("￥0");
            $("span.real_income").html("￥0");
            return
        }
        sendRequest("/api/market/batch/fee", {
            data: {
                game: game,
                prices: prices.join(",")
            },
            dataType: "json",
            method: "GET",
            showLoading: false,
            success: function(data) {
                if (data.code == "OK") {
                    var total_fee = data.data.total_fee;
                    $("span.sale_fee").html("￥" + total_fee);
                    $("span.real_income").html(formatPriceYuan("" + (total_price - parseFloat(total_fee)).toFixed(2)))
                } else {
                    Buff.toast(data.error, {
                        type: "error"
                    })
                }
            }
        })
    };
    var init = function() {
        gameNavigator.setKeepParams(["mode"]);
        $(".cancel-bundle").click(function() {
            var orderid = $(this).parents("tr").data("orderid");
            var mode_desc = getParams().mode == 4 ? i18n("private_transactions") : i18n("package_deal");
            Buff.alert({
                title: i18n("confirm_to_cancel_the_transaction"),
                message: i18n("the_shelves_after_the_goods") + mode_desc + "?",
                success: function() {
                    sendRequest("/api/market/sell_order/cancel", {
                        method: "POST",
                        data: {
                            sell_orders: [orderid],
                            game: g.game
                        },
                        success: function(data) {
                            if (data.code !== "OK") {
                                Buff.toast(data.error, {
                                    type: "error"
                                });
                                return
                            }
                            if (data.data[orderid] !== "OK") {
                                Buff.toast(data.data[orderid], {
                                    type: "error"
                                });
                                return
                            }
                            Buff.toast(i18n("shelves_successful"), {
                                type: "success"
                            });
                            setTimeout(function() {
                                window.location.reload()
                            }, 1e3)
                        }
                    })
                }
            })
        });
        $(".edit-bundle").click(function() {
            assets = [{
                price: 0
            }];
            var orderid = $(this).parents("tr").data("orderid");
            sendRequest("/api/market/bundle_detail/" + orderid, {
                data: {
                    game: g.game
                },
                method: "GET",
                showLoading: false,
                success: function(data) {
                    if (data.code !== "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        return
                    }
                    var selected = [];
                    var items = {};
                    var sum_price = 0;
                    data.data.items.forEach(function(asset_info) {
                        selected.push(asset_info.assetid);
                        items[asset_info.assetid] = {
                            asset_info: asset_info,
                            goods_id: asset_info.goods_id
                        };
                        sum_price += parseFloat(data.data.goods_infos[asset_info.goods_id].steam_price_cny)
                    });
                    var html = template_render("bundle_pat", {
                        selected: selected,
                        items: items,
                        goods_infos: data.data.goods_infos,
                        sum_price: sum_price,
                        isChange: 1
                    });
                    $("#popup-container").html(html);
                    Popup.show("j_popup_trans");
                    $("#j_popup_trans input[name=price]").val(data.data.price).trigger("input").trigger("change");
                    $("#j_popup_trans input[name=description]").val(data.data.description).trigger("input").trigger("change");
                    var bs = bundleSell();
                    (data.data.images || []).forEach(function(image) {
                        bs.addUploadItem(image)
                    });
                    $("#j_popup_trans .confirm").attr("data-orderid", orderid)
                },
                error: function() {
                    Buff.toast(i18n("get_the_package_deal_failed"), {
                        type: "error"
                    })
                }
            })
        });
        $(document).on("click", "#j_popup_trans .confirm", function() {
            var price = $("#j_popup_trans input[name=price]").val();
            var description = $("#j_popup_trans input[name=description]").val();
            if (!price || !price.length) {
                Buff.toast(i18n("please_enter_pricing"), {
                    type: "error"
                });
                return
            }
            var images = [];
            $("#j_popup_trans #uploaded-pics img.success").each(function(idx, ele) {
                images.push($(ele).data("src"))
            });
            if ($(".upload-item:not(.success)").length > 0) {
                Buff.toast(i18n("a_picture_is_not_uploaded"), {
                    type: "error"
                });
                return
            }
            var orderid = $(this).data("orderid");
            sendRequest("/api/market/sell_order/change", {
                method: "POST",
                dataType: "json",
                data: {
                    game: g.game,
                    sell_orders: [{
                        sell_order_id: orderid,
                        price: price,
                        desc: description,
                        images: images
                    }]
                },
                success: function(data) {
                    if (data.code !== "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        })
                    } else {
                        Buff.toast(i18n("modify_the_success"), {
                            type: "success"
                        });
                        setTimeout(function() {
                            window.location.reload()
                        }, 1e3)
                    }
                }
            })
        });
        $(document).on("mousemove", "#j_popup_trans", function() {
            update_fee()
        });
        $(document).on("input", "#j_popup_trans input[name=price]", function() {
            var index = $(this).data("index") - 1;
            var price = parseFloat($(this).val());
            if (check_price_value($(this).val())) {
                $(this).removeClass("i_Text_error")
            } else {
                $(this).addClass("i_Text_error")
            }
            assets[index].price = price;
            should_update_fee = true
        });
        $(document).on("change", "#j_popup_trans input[name=price]", function() {
            var price = parseFloat($(this).val());
            if (check_price_value($(this).val(), true)) {
                update_fee()
            }
        });
        $(document).on("click", ".copy-private-link", function() {
            setClipboard($(this).data("link"));
            Buff.toast(i18n("replicated"), {
                type: "success"
            })
        })
    };
    return {
        init: init
    }
};
var bundleSell = function(fp) {
    var images = [];
    var maximum = 5;
    var thumbnail = function(src) {
        if (src.indexOf("?") != -1) {
            return src
        }
        return src + "?fop=imageView/0/w/96/h/96"
    };
    var addUploadItem = function(src) {
        var uploadItem = $("<div />", {
            class: "upload-item"
        });
        uploadItem.append($("<img />"));
        uploadItem.append($('<a href="javascript:;" class="delete-upload-img"><i class="icon icon_delete"></i></a>'));
        uploadItem.append($('<div class="upload-single-progressing"><span>0%</span></div>'));
        uploadItem.append($('<div class="upload-single-fail"><span>重试</span></div>'));
        $("#uploaded-pics").append(uploadItem);
        var count = parseInt($("#uploaded-count").text()) + 1;
        $("#uploaded-count").text(count);
        if (count >= maximum) {
            $("#upload-bundle-img-btn").hide();
            $("#click-to-upload").hide()
        }
        if (src) {
            uploadItem.find("img").addClass("success").attr("src", thumbnail(src)).data("src", src);
            uploadItem.addClass("success")
        } else {
            uploadItem.addClass("progressing")
        }
        return uploadItem
    };
    var doUpload = function(file) {
        var uploadItem = addUploadItem(undefined);
        var reader = new FileReader;
        reader.onload = function(e) {
            uploadItem.find("img").attr("src", e.target.result)
        }
        ;
        reader.readAsDataURL(file);
        var options = {
            file: file,
            upload_url: fp.url,
            max_file_size: fp.max_size,
            token: fp.token,
            callback: function(data) {
                uploadItem.find("img").addClass("success").attr("src", thumbnail(data.url)).data("src", data.url);
                uploadItem.removeClass("progressing").addClass("success")
            },
            onprogress: function(e) {
                if (e.lengthComputable) {
                    var percentVal = (e.loaded / e.total * 100).toFixed(2);
                    uploadItem.find(".upload-single-progressing").text(percentVal + "%")
                }
            },
            error: function(msg) {
                Buff.toast(msg, {
                    type: "error"
                });
                uploadItem.removeClass("progressing").addClass("fail");
                uploadItem.find(".upload-single-fail span").css("cursor", "pointer").off("click").on("click", function() {
                    uploadItem.removeClass("fail").addClass("progressing");
                    uploadFile(options)
                })
            }
        };
        uploadFile(options)
    };
    var init = function() {
        $(document).on("click", "#upload-bundle-img", function() {
            $(this).val("")
        });
        $(document).on("change", "#upload-bundle-img", function(e) {
            var files = e.target.files;
            var newLength = files.length + $("#uploaded-pics img").length;
            if (newLength > maximum) {
                Buff.toast("最多上传" + maximum + "张图片", {
                    type: "error"
                });
                return
            }
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                doUpload(file)
            }
        });
        $(document).on("click", ".delete-upload-img", function() {
            $(this).parents(".upload-item").remove();
            $("#uploaded-count").text(parseInt($("#uploaded-count").text()) - 1);
            $("#upload-bundle-img-btn").show();
            $("#click-to-upload").show()
        });
        $(document).on("click", "#upload_file_label", function() {
            $("#upload-bundle-img").click()
        })
    };
    return {
        addUploadItem: addUploadItem,
        init: init
    }
};
var evaluation = function() {
    var current_user_steamid = null;
    var getSteamidHistory = function() {
        var history = localStorage.getItem("evaluation_history");
        if (history) {
            return history.split(",")
        } else {
            return []
        }
    };
    var addSteamidHistory = function(steamid) {
        var items = getSteamidHistory();
        if (items.indexOf(steamid) == -1) {
            items.unshift(steamid);
            localStorage.setItem("evaluation_history", items)
        }
    };
    var delSteamidHistory = function(steamid) {
        var items = getSteamidHistory();
        var new_items = [];
        for (var i = 0; i < items.length; i++) {
            if (items[i] != steamid)
                new_items.push(items[i])
        }
        localStorage.setItem("evaluation_history", new_items)
    };
    var init = function(game, steamid) {
        current_user_steamid = steamid;
        var hash_params = getParamsFromHash();
        for (var key in hash_params) {
            if (["min_price", "max_price", "search"].indexOf(key) > -1) {
                $("input[name=" + key + "]").val(hash_params[key])
            } else if (key == "category_group") {
                Buff.setCompValue("search-category", hash_params[key])
            } else {
                Buff.setCompValue("search-" + key, hash_params[key])
            }
        }
        $(document).on("focus", "input[name=steamid]", function() {
            var items = getSteamidHistory();
            var html = "";
            for (var i = 0; i < items.length; i++) {
                html += '<li><div class="steamid-item">' + items[i] + '</div><div class="steamid-delete icon icon_delete"></div></li>'
            }
            $(".steamid-history ul").html(html);
            $(".steamid-history").css({
                left: $(this).offset().left + "px"
            });
            $(".steamid-history").show()
        });
        $(document).on("blur", "input[name=steamid]", function() {
            setTimeout(function() {
                $(".steamid-history").hide()
            }, 200)
        });
        $(document).on("click", ".steamid-history li", function() {
            var steamid = $(this).find(".steamid-item").text();
            $("input[name=steamid]").val(steamid)
        });
        $(document).on("click", ".steamid-history li .steamid-delete", function(event) {
            event.stopPropagation();
            var steamid = $(this).parent().find(".steamid-item").text();
            delSteamidHistory(steamid)
        });
        var query_data = getParams();
        $(document).on("change", ".w-Select_game", function() {
            var hash_data = getParamsFromHash();
            for (var key in hash_data) {
                hash_data[key] = ""
            }
            updateHashData(hash_data);
            var data = {
                game: $(this).attr("value"),
                steamid: $("input[name=steamid]").val()
            };
            updateSearchData(data)
        });
        $(document).on("change", ".w-Select:not(.w-Select_game)", function() {
            updateHash($(this).attr("name"), $(this).attr("value"))
        });
        $(document).on("change", ".w-Tag", function() {
            updateHash($(this).attr("name"), $(this).attr("value"))
        });
        $(document).on("change", ".w-SelHero", function() {
            updateHash("hero", $(this).attr("value"))
        });
        $(document).on("change", ".w-Search input", function() {
            updateHash("search", $(this).val())
        });
        $(document).on("change", "input[name=min_price]", function() {
            updateHash("min_price", $(this).val())
        });
        $(document).on("change", "input[name=max_price]", function() {
            updateHash("max_price", $(this).val())
        });
        $(document).on("click", ".w-Counter-pannel .i_Btn_sub", function() {
            updateHashData({
                min_price: "",
                max_price: ""
            })
        });
        $(document).on("change", ".w-Select-Multi", function() {
            var name = $(this).attr("name");
            if (name == "rarity") {
                var val = $(this).attr("value");
                if (typeof val != "undefined" && val != "0") {
                    updateHashData({
                        rarity: val
                    })
                }
                return
            }
            var category = $(".w-Select-Multi").attr("value");
            if (typeof category != "undefined") {
                var category_group = $('.w-Select-Multi h6[value="' + category + '"]').attr("value");
                if (category == category_group) {
                    updateHashData({
                        category_group: category,
                        category: ""
                    })
                } else {
                    updateHashData({
                        category_group: "",
                        category: category
                    })
                }
            }
        });
        $(document).on("click", "#btn-refresh", function() {
            refresh(null, 1)
        });
        Buff.pricePatten("input[name=min_price]");
        Buff.pricePatten("input[name=max_price]");
        var refresh = function(page_num, force) {
            var steamid = query_data.steamid;
            $("#j_list_card").showLoading();
            var query = getParamsFromHash();
            query.game = game;
            query.steamid = steamid;
            query.page_num = page_num || query.page_num;
            query.force = force || 0;
            if (game == "csgo") {
                query.state = query.state || "all"
            }
            sendRequest("/api/market/evaluation", {
                data: query,
                dataType: "json",
                method: "GET",
                showLoading: false,
                timeout: BuffConfig.STEAM_TIMEOUT,
                ignoreCode: ["Backpack Is Private"],
                success: function(data) {
                    $("#j_list_card").removeLoading();
                    var html = "";
                    if (data.code == "OK") {
                        $("#total-count").text(data.data.total_count);
                        $("#total-value").text("$" + (data.data.total_price / 100).toFixed(2));
                        html = template_render("evaluation_card_list_pat", data.data);
                        if (data.data.items.length > 0) {
                            addSteamidHistory(steamid)
                        }
                        renderPagination({
                            total_count: data.data.total_count,
                            page_size: data.data.page_size,
                            page_num: data.data.page_num,
                            show_size_select: true,
                            onPageClick: function(page_num, event) {
                                event.preventDefault();
                                updateHash("page_num", page_num);
                                window.scrollTo(0, 0)
                            }
                        })
                    } else if (data.code == "Backpack Is Private") {
                        html = '<div class="nodata">                                    <p><i class="icon icon_unbind"></i></p>                                    <p>' + data.error + "</p>";
                        if (steamid == current_user_steamid) {
                            html += '<div><a href="https://steamcommunity.com/my/edit/settings" target="_blank" class="i_Btn i_Btn_hollow">' + i18n("go_to_settings") + "</a></div></div>"
                        } else {
                            html += "</div>"
                        }
                        $(".pager").html("")
                    } else {
                        Buff.toast(data.error)
                    }
                    $("#j_list_card").html(html);
                    $("img.lazy").lazyload()
                },
                error: function(resp) {
                    $("#j_list_card").removeLoading()
                }
            })
        };
        if (query_data.steamid) {
            refresh()
        }
        $(window).on("hashchange", function() {
            refresh()
        });
        if (getParams().game == "pubg_recycle") {
            updateSearch("game", "pubg")
        }
    };
    return {
        init: init
    }
};
var lockCompensate = function() {
    var period;
    var show_goods = function() {
        var page_num = getParamsFromHash().page_num || 1;
        var data = {
            period: period,
            page_num: page_num
        };
        sendRequest("/api/market/lock/goods", {
            data: data,
            dataType: "json",
            method: "GET",
            showLoading: true,
            success: function(data) {
                if (data.data.items.length == 0) {
                    $("#compensate").addClass("i_Btn_disabled")
                }
                var html = template_render("goods_list_pat", data.data);
                $("#j_list_card").html(html);
                renderPagination({
                    total_count: data.data.total_count,
                    page_size: data.data.page_size,
                    page_num: data.data.page_num,
                    show_size_select: false,
                    size_selects: [70, 140, 210],
                    onPageClick: function(page, event) {
                        event.preventDefault();
                        updateHash("page_num", page);
                        show_goods()
                    }
                });
                html = template_render("brief_info_pat", {
                    lock_goods_count: data.data.total_count
                });
                $(".brief-info").html(html);
                $("#total_compensate_count").text(data.data.total_count);
                $("#total_compensate_price").text(data.data.total_compensation)
            }
        })
    };
    var compensate = function() {
        sendRequest("/api/market/lock/compensate", {
            data: {
                period: period
            },
            dataType: "json",
            method: "POST",
            showLoading: true,
            success: function(data) {
                Buff.toast(i18n("to_receive_the_success"), {
                    type: "success"
                });
                Popup.hide();
                show_goods()
            }
        })
    };
    var init = function(current_period) {
        period = current_period;
        show_goods();
        $("#compensate").click(function() {
            Popup.show("j_popup_compensate")
        });
        $("#j_popup_compensate .i_Btn_main").click(function() {
            if (!$("#agreen").hasClass("on")) {
                Buff.toast(i18n("please_tick_the_below_statement"), {
                    type: "warning"
                });
                return
            }
            compensate()
        })
    };
    return {
        init: init
    }
}();
var sellingStat = function(chartData) {
    var showChart = function(input, field) {
        var ctx = document.getElementById("myChart");
        var labels = [];
        var values = [];
        Object.keys(input).forEach(function(ts) {
            labels.push(moment(parseInt(ts)).format("YYYY-MM-DD"));
            if (field == "amount") {
                values.push(g.currency.rate_base_cny * parseFloat(input[ts][field]))
            } else {
                values.push(parseFloat(input[ts][field]))
            }
        });
        var amountTicks = {
            suggestedMax: Math.max(Math.max.apply(null, values) * 1.03, .01),
            beginAtZero: true,
            callback: function(value) {
                return g.currency.symbol + " " + value
            }
        };
        var countTicks = {
            suggestedMax: Math.max(Math.max.apply(null, values) * 1.03, 1),
            beginAtZero: true,
            callback: function(value) {
                return value
            }
        };
        var datasets = [];
        if (field == "count") {
            datasets.push({
                label: i18n("sold_number_of_pieces"),
                data: values,
                borderColor: "#426BBB",
                backgroundColor: "#426BBB",
                fill: false,
                borderWidth: 2
            })
        } else {
            datasets.push({
                label: i18n("sale_amount"),
                data: values,
                borderColor: "#EEA20E",
                backgroundColor: "#EEA20E",
                fill: false,
                borderWidth: 2
            })
        }
        var myChart = new Chart(ctx,{
            type: "line",
            data: {
                labels: labels,
                datasets: datasets
            },
            options: {
                borderWidth: 1,
                tooltips: {
                    mode: "index",
                    axis: "x",
                    displayColors: false,
                    intersect: false,
                    callbacks: {
                        label: function(tooltipItem, _data) {
                            if (field == "count") {
                                return i18n("sale_number_") + tooltipItem.yLabel
                            } else {
                                return i18n("sale_amount_yuan") + g.currency.symbol + " " + tooltipItem.yLabel
                            }
                        }
                    },
                    backgroundColor: "rgba(255,255,255,0.8)",
                    titleFontColor: "#000",
                    bodyFontColor: "#000",
                    borderWidth: 1,
                    borderColor: "#7cb5ec"
                },
                layout: {
                    padding: {
                        left: 50,
                        right: 50,
                        top: 0,
                        bottom: 50
                    }
                },
                legend: {
                    display: false
                },
                elements: {
                    point: {
                        radius: 3,
                        borderWidth: 0,
                        hitRadius: 6
                    },
                    line: {
                        tension: 0
                    }
                },
                scales: {
                    xAxes: [{
                        type: "time",
                        bounds: "ticks",
                        distribution: "linear",
                        ticks: {
                            source: "labels"
                        },
                        time: {
                            unit: "day",
                            displayFormats: {
                                day: "MM-DD"
                            }
                        },
                        gridLines: {}
                    }],
                    yAxes: [{
                        id: "A",
                        position: "left",
                        ticks: field == "count" ? countTicks : amountTicks
                    }]
                }
            }
        })
    };
    var init = function() {
        $("#j_fold-handler").click(function() {
            if ($(this).hasClass("on")) {
                $(this).removeClass("on").find("span").html(i18n("view_more"));
                $("#j_sold-count").animate({
                    height: 170
                }, "fast")
            } else {
                $(this).addClass("on").find("span").html(i18n("click_to_collapse"));
                $("#j_sold-count").animate({
                    height: 356
                }, "fast")
            }
        });
        $("#chart-switcher span").on("click", function() {
            var field = $(this).data("field");
            $("#myChart").parent().html('<canvas id="myChart"></canvas>');
            showChart(chartData, field)
        });
        showChart(chartData, "amount");
        g.game = getParams().game
    };
    return {
        init: init
    }
};
var SteamAssetRemark = function() {
    var game = g.game;
    var init = function() {
        $(document).off("click", ".asset-remark-edit");
        $(document).on("click", ".asset-remark-edit", function(e) {
            e.preventDefault();
            e.stopPropagation();
            var $remark_el = $(this);
            var assetid = $(this).data("assetid");
            var remark = $(this).data("content") || "";
            var buy_price = $(this).data("buy_price") || "";
            var buy_price_note = "";
            var $popup = $("#j_popup_common_notes");
            var $note = $popup.find("textarea");
            var $buy_price_quick = $popup.find(".auto-fit-buy-price");
            $buy_price_quick.find("span").text("");
            $buy_price_quick.hide();
            $buy_price_quick.parent().hide();
            $note.val("");
            setTimeout(function() {
                $note.val("");
                $note.focus().val(remark);
                $note.trigger("input")
            }, 300);
            if (buy_price) {
                buy_price_note = "￥" + buy_price + i18n("purchased");
                $buy_price_quick.find("span").text(buy_price_note);
                $buy_price_quick.show();
                $buy_price_quick.parent().show()
            }
            if (remark) {
                $popup.find(".popup-title").text(i18n("edit_notes"))
            } else {
                $popup.find(".popup-title").text(i18n("add_notes"))
            }
            $buy_price_quick.unbind("click").click(function(e) {
                e.preventDefault();
                var origin_content = $note.val();
                if (buy_price_note) {
                    var content = origin_content + buy_price_note;
                    if (content.length > 40) {
                        content = content.slice(0, 40)
                    }
                    $note.val("");
                    $note.focus().val(content);
                    $note.trigger("input")
                }
            });
            $popup.find(".confirm:not(.i_Btn_disabled)").unbind("click").click(function(e) {
                e.preventDefault();
                e.stopPropagation();
                if ($note.val().length > 40) {
                    Buff.toast(i18n("notes_exceed_max_len"), {
                        type: "warning"
                    });
                    return
                }
                var assets = [{
                    remark: $note.val(),
                    assetid: assetid
                }];
                sendRequest("/api/market/steam_asset_remark/change", {
                    data: {
                        game: game,
                        assets: assets
                    },
                    method: "POST",
                    timeout: BuffConfig.STEAM_TIMEOUT + 1e3 * assets.length,
                    success: function(data) {
                        if (data.code == "OK") {
                            Buff.toast(i18n("submitted"), {
                                type: "success"
                            });
                            var new_content = $note.val();
                            if (!new_content) {
                                if ($remark_el.hasClass("without-class-change")) {
                                    $remark_el.text("");
                                    $remark_el.hide()
                                } else {
                                    $remark_el.removeClass("shalow-btn_long");
                                    $remark_el.addClass("shalow-btn_hidden");
                                    $remark_el.text(i18n("notes"))
                                }
                            } else {
                                if (!$remark_el.hasClass("without-class-change")) {
                                    $remark_el.removeClass("shalow-btn_hidden");
                                    $remark_el.addClass("shalow-btn_long");
                                    $remark_el.text(new_content)
                                } else {
                                    $remark_el.text(i18n("notes_desc") + new_content)
                                }
                            }
                            $remark_el.data("content", new_content);
                            if (!$remark_el.hasClass("without-class-change")) {
                                if (!new_content) {
                                    if ($remark_el.hasClass("remark_without_stickers")) {
                                        $remark_el.parent().removeClass("tagBoxB_inline")
                                    } else if ($remark_el.hasClass("with-gem-list") && $remark_el.hasClass("with-other-gem-list")) {
                                        $remark_el.parent().removeClass("tagBoxB_RT2");
                                        $remark_el.parent().addClass("tagBoxB_RT")
                                    } else if ($remark_el.hasClass("with-gem-list")) {
                                        $remark_el.parent().addClass("tagBoxB_RT")
                                    } else {
                                        $remark_el.parent().removeClass("tagBoxB_RT")
                                    }
                                } else {
                                    if ($remark_el.hasClass("remark_without_stickers")) {
                                        $remark_el.parent().addClass("tagBoxB_inline")
                                    } else if ($remark_el.hasClass("with-gem-list") && $remark_el.hasClass("with-other-gem-list")) {
                                        $remark_el.parent().addClass("tagBoxB_RT2");
                                        $remark_el.parent().removeClass("tagBoxB_RT")
                                    } else if ($remark_el.hasClass("with-gem-list") || $remark_el.hasClass("with-other-gem-list")) {
                                        $remark_el.parent().addClass("tagBoxB_RT");
                                        $remark_el.parent().removeClass("tagBoxB_RT2")
                                    }
                                }
                            }
                            Popup.hide()
                        } else {
                            Buff.toast(data.error || data.code, {
                                type: "warning"
                            })
                        }
                    }
                })
            });
            Popup.show("j_popup_common_notes")
        })
    };
    return {
        init: init
    }
};
var bindCard = function() {
    var WAIT_TIME = 60;
    var wait = WAIT_TIME;
    var realname = null;
    var max_bank_card_count;
    var auto_highlight_bank_card = false;
    var send_authcode_status = false;
    function luhm_check(bankno) {
        var bankno_length = bankno.length;
        var no_sum = 0;
        for (var i = 1; i < bankno_length; i++) {
            if (i % 2 == 1) {
                var double_odd = parseInt(bankno[bankno_length - 1 - i]) * 2;
                no_sum += double_odd > 9 ? double_odd - 9 : double_odd
            } else {
                no_sum += parseInt(bankno[bankno_length - 1 - i])
            }
        }
        if (parseInt(bankno[bankno_length - 1]) == no_sum * 9 % 10) {
            return true
        } else {
            return false
        }
    }
    var countdown_handler = undefined;
    function countdown(o) {
        if (wait == 0) {
            o.removeClass("i_Btn_disabled");
            o.text(i18n("get_the_verification_code"));
            wait = WAIT_TIME;
            countdown_handler = undefined
        } else {
            o.addClass("i_Btn_disabled");
            o.html(i18n("resend") + "<small>(" + wait + ")</small>");
            wait--;
            countdown_handler = setTimeout(function() {
                countdown(o)
            }, 1e3)
        }
    }
    var input_error = function(popup_id) {
        var show = function(error, $item) {
            var $popup = $("#" + popup_id);
            if (typeof error == "string") {
                if ($item) {
                    $item.siblings(".error").text(error)
                } else {
                    $popup.find(".c_Error").text(error)
                }
            }
            if ($item) {
                $item.parent().addClass("i_Text_error")
            }
        };
        var clear = function($item) {
            var $popup = $("#" + popup_id);
            if ($item) {
                $item.siblings(".error").text("");
                $item.parent().removeClass("i_Text_error")
            } else {
                $popup.find(".c_Error").html("&nbsp;")
            }
        };
        var clear_all = function() {
            var $popup = $("#" + popup_id);
            $popup.find(".i_Text_error").removeClass("i_Text_error");
            $popup.find(".error").text("");
            $popup.find(".c_Error").html("&nbsp;")
        };
        return {
            show: show,
            clear: clear,
            clear_all: clear_all
        }
    };
    var check_realname = function(realname) {
        if (!realname) {
            return i18n("the_real_name_can_not")
        } else if (realname.length > 64) {
            return i18n("the_system_supports_the_maximum")
        }
    };
    var check_id_card = function(id_card) {
        var Validator = new IDValidator(GB2260);
        if (!id_card) {
            return i18n("id_number_can_not_be")
        } else if (!Validator.isValid(id_card)) {
            return i18n("id_card_number_errors_please")
        }
    };
    var init_card_popup = function(realname_info, for_cert, bind_card_callback) {
        realname = realname_info;
        if (!bind_card_callback) {
            bind_card_callback = function() {}
        }
        var card_input_error = input_error("j_popup_card");
        var card_input = {
            data: {},
            error_msg: "",
            show_error: true,
            add_text_error: function($item) {
                if (this.show_error) {
                    card_input_error.show(this.error_msg, $item)
                }
            },
            get: function(need_authcode) {
                var $popup_card = $("#j_popup_card");
                var error = false;
                card_input_error.clear_all();
                this.error_msg = "";
                var $realname = $popup_card.find("input[name=realname]");
                if ($realname.length > 0) {
                    var realname = $realname.val().replace(/\s*/g, "");
                    this.error_msg = check_realname(realname);
                    if (this.error_msg) {
                        this.add_text_error($realname);
                        return undefined
                    }
                    this.data["realname"] = realname
                }
                var $id_card = $popup_card.find("input[name=id_card]");
                if ($id_card.length > 0) {
                    var id_card = $id_card.val().replace(/\s*/g, "");
                    this.error_msg = check_id_card(id_card);
                    if (this.error_msg) {
                        this.add_text_error($id_card);
                        return undefined
                    }
                    this.data["id_card"] = id_card
                }
                var $card_number = $popup_card.find("input[name=card_number]");
                var card_number = $card_number.val().replace(/\s*/g, "");
                var bank_id = $popup_card.find("input[name=bank_id]").val();
                var card_type = $popup_card.find("input[name=card_type]").val();
                if (!card_number) {
                    this.error_msg = i18n("the_bank_card_number_can");
                    this.add_text_error($card_number);
                    return undefined
                }
                if (!bank_id) {
                    this.error_msg = i18n("currently_does_not_support_the")
                } else if (bank_id != "9998" && bank_id != "9999" && !luhm_check(card_number)) {
                    this.error_msg = i18n("the_bank_card_number_errors")
                } else if (card_type == "credit") {
                    this.error_msg = i18n("not_support_credit_card")
                }
                if (this.error_msg) {
                    this.add_text_error();
                    return undefined
                }
                this.data["card_number"] = card_number;
                this.data["bank_id"] = bank_id;
                this.data["card_type"] = card_type;
                var $mobile = $popup_card.find("input[name=mobile]");
                var mobile = $mobile.val().replace(/\s*/g, "");
                if (!mobile) {
                    this.error_msg = i18n("the_phone_number_cannot_be")
                } else if (!/^(13|14|15|16|17|18|19)\d{9}$/.test(mobile)) {
                    this.error_msg = i18n("the_phone_number_is_incorrect")
                }
                if (this.error_msg) {
                    this.add_text_error($mobile);
                    return undefined
                }
                this.data["mobile"] = mobile;
                if (need_authcode) {
                    var card_id = $popup_card.find("input[name=card_id]").val();
                    if (!card_id) {
                        this.error_msg = i18n("please_get_a_sms_verification")
                    }
                    if (this.error_msg) {
                        this.add_text_error();
                        return undefined
                    }
                    this.data["card_id"] = card_id;
                    var $authcode = $popup_card.find("input[name=authcode]");
                    var authcode = $authcode.val().replace(/\s*/g, "");
                    if (!authcode) {
                        this.error_msg = i18n("verification_code_cannot_be_empty")
                    } else if (!/^\d{6}$/.test(authcode)) {
                        this.error_msg = i18n("the_verification_code_is_incorrect")
                    }
                    if (this.error_msg) {
                        this.add_text_error($authcode);
                        return undefined
                    }
                    this.data["authcode"] = authcode;
                    if ($("#agreement").length > 0 && !$("#agreement").hasClass("on")) {
                        this.error_msg = i18n("need_to_first_agree_to");
                        this.add_text_error();
                        return undefined
                    }
                }
                return true
            },
            clear: function() {
                $("input[name=card_number]").val("");
                $("input[name=mobile]").val("");
                $("input[name=authcode]").val("")
            },
            show_bank_info: function(card_info) {
                $("input[name=bank_id]").val(card_info["bank_id"]);
                $("input[name=card_type]").val(card_info["card_type"]);
                $(".card-name").find("i").addClass("b_" + card_info["bank_style_id"]).next().text(card_info["bank_name"]);
                $(".card-name").show()
            },
            clear_bank_info: function() {
                $("input[name=bank_id]").val("");
                $("input[name=card_type]").val("");
                var classname = $(".card-name").find("i").attr("class");
                $(".card-name").find("i").attr("class", classname.replace(/b_\d+/, "")).next().text("");
                $(".card-name").hide()
            }
        };
        var check_card = function(card_no) {
            card_input.clear_bank_info();
            var card_length = card_no.length;
            if (card_length < 16 || card_length > 19)
                return;
            if (/^6666/.test(card_no)) {
                if (card_length != 16 && card_length != 18)
                    return
            } else if (!luhm_check(card_no)) {
                return
            }
            sendRequest("/api/asset/get_card_info/", {
                data: {
                    card_number: card_no
                },
                method: "get",
                dataType: "json",
                showLoading: false,
                success: function(data) {
                    if (data.code == "Card Bank Empty" || data.code == "Card Not Supported") {
                        card_input_error.show(data.error, $("input[name=card_number]"));
                        return
                    } else if (data.code != "OK") {
                        return
                    }
                    card_input.show_bank_info(data.data)
                }
            })
        };
        var send_authcode = function() {
            if (card_input.get(false) == undefined) {
                return
            }
            var card_info = card_input.data;
            $("input[name=card_id]").val("");
            var timeout = ENV == "prod" ? 5e3 : 15e3;
            sendRequest("/api/asset/bind_card/", {
                data: card_info,
                method: "post",
                dataType: "json",
                timeout: timeout,
                success: function(data) {
                    if (data.code != "OK") {
                        if (data.code == "Card Type Error") {
                            card_info.add_text_error(i18n("recharge_with_cash_only_support"))
                        } else {
                            Buff.alert({
                                type: "error",
                                title: i18n("bound_to_fail"),
                                message: data.code == "Epay Response Error" ? data.error || i18n("tied_the_card_fails_please") : data.error,
                                hideCancel: true
                            })
                        }
                        return
                    }
                    $("input[name=card_id]").val(data.data.card_id);
                    countdown($("#send_authcode"));
                    send_authcode_status = true
                }
            })
        };
        var bind_card = function() {
            if (card_input.get(true) == undefined) {
                return
            }
            var card_info = card_input.data;
            sendRequest("/api/asset/bind_card_verify/", {
                data: card_info,
                method: "post",
                dataType: "json",
                success: function(data) {
                    if (data.code != "OK") {
                        if (data.code == "Card Type Error") {
                            card_info.add_text_error(i18n("recharge_with_cash_only_support"))
                        } else {
                            Buff.alert({
                                type: "error",
                                title: "绑定失败",
                                message: data.code == "Epay Response Error" ? data.error || i18n("tied_the_card_fails_please") : data.error,
                                hideCancel: true
                            })
                        }
                        return
                    }
                    Buff.toast(i18n("the_binding_is_successful"), {
                        type: "success"
                    });
                    sleep(1e3);
                    Popup.hide();
                    if (!realname) {
                        realname = {
                            name: card_info["realname"],
                            id_card: card_info["id_card"]
                        };
                        init_card_popup(realname);
                        wait = 0
                    } else {
                        card_input.clear();
                        card_input.clear_bank_info();
                        wait = 0
                    }
                    bind_card_callback(data.data.card_info)
                }
            })
        };
        $("#j_popup_card").remove();
        $("body").append(template_render("popup_card_pat", {
            realname: realname,
            for_cert: for_cert
        }));
        $("input[name=card_number]").unbind().bind("input propertychange", function(e) {
            var card_number = $(this).val().replace(/\s*/g, "");
            if (card_number != "" && !/^\d+$/.test(card_number)) {
                return
            }
            card_input_error.clear($(this));
            if (!card_number) {
                $(".card-tip").hide();
                card_input.clear_bank_info()
            } else {
                $(".card-tip").show();
                var formated_card_number = "";
                for (var i = 0; i < card_number.length; ++i) {
                    if (i % 4 == 3) {
                        formated_card_number += card_number[i] + " "
                    } else {
                        formated_card_number += card_number[i]
                    }
                }
                $(".card-tip span:first").text(formated_card_number);
                check_card(card_number)
            }
        }).bind("mouseleave focusout", function() {
            $(".card-tip").hide()
        });
        $("#agreement").unbind().bind("click", function(event) {
            if ($(this).hasClass("on")) {
                $(this).removeClass("on");
                $("#bind_card").addClass("i_Btn_disabled")
            } else {
                $(this).addClass("on");
                $("#bind_card").removeClass("i_Btn_disabled")
            }
            event.stopPropagation()
        });
        $("#send_authcode").unbind().bind("click", function() {
            send_authcode()
        });
        $("#bind_card").unbind().bind("click", function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return false
            }
            bind_card()
        });
        $("#change_to_zhima").unbind().bind("click", function() {
            Popup.hide();
            Popup.show("j_popup_zhima")
        });
        init_zhima_cert(bind_card_callback)
    };
    var get_selected_card = function() {
        var $selected_card_item = $("#bank_card_select .select-list-item.on");
        if ($selected_card_item.length > 0) {
            var card_id = $selected_card_item.attr("card_id");
            var mobile = $selected_card_item.attr("mobile");
            var card_number = $selected_card_item.attr("card_number");
            var support_withdraw = $selected_card_item.attr("support_withdraw") != undefined ? true : false;
            return {
                card_id: card_id,
                mobile: mobile,
                support_withdraw: support_withdraw,
                card_number: card_number
            }
        }
    };
    var highlight_card = function() {
        auto_highlight_bank_card = true;
        var $selected = $("#bank_card_select .selected");
        if ($selected.find(".bank-name").length > 0) {
            $selected.addClass("on")
        }
    };
    var cancel_highlight_card = function() {
        auto_highlight_bank_card = false;
        $("#bank_card_select .selected").removeClass("on")
    };
    var init_card_list = function(realname_info, bank_card_count, select_card_callback) {
        realname = realname_info;
        max_bank_card_count = bank_card_count;
        if (!select_card_callback) {
            select_card_callback = function() {}
        }
        var show_selected_card = function(selected_card) {
            if (!selected_card) {
                if ($("#bank_card_select .select-list-item").hasClass("on")) {
                    selected_card = $("#bank_card_select .select-list-item.on")
                } else {
                    selected_card = $("#bank_card_select .select-list-item").first()
                }
            }
            var $selected = $("#bank_card_select .selected");
            if (!selected_card || selected_card.hasClass("card-list-add")) {
                var $target = $('<i class="icon icon_select_bank_small"></i><span class="c_Gray">' + i18n("please_select_the_bank_account") + "</span>");
                $selected.html($target);
                return
            }
            var style_id = selected_card.attr("bank_style_id");
            var name = selected_card.attr("bank_name");
            var number = selected_card.attr("card_number");
            var $target = $('<i class="icon icon_select_bank_small"></i><span class="bank-name">' + name + '</span><span class="card-number">' + number + "</span>");
            $selected.html($target);
            if (auto_highlight_bank_card) {
                $selected.addClass("on")
            }
            if (!selected_card.hasClass("card-list-add")) {
                selected_card.siblings().removeClass("on");
                selected_card.addClass("on")
            }
        };
        var add_card = function(card_info) {
            var $new_card = $(template_render("card_detail_pat", {
                card: card_info
            }));
            $("#bank_card_select .select-list-item:last").before($new_card);
            $("#bank_card_select").show();
            var current_card_count = $("#bank_card_select .select-list-item").length - 1;
            if (current_card_count >= max_bank_card_count) {
                $("#bank_card_select .card-list-add").hide()
            }
            if (current_card_count == 1) {
                $("#bank_card_select .card-list-add span").text(i18n("add_the_other_card"))
            }
            show_selected_card($new_card)
        };
        var delete_card = function($item) {
            var card_id = $item.attr("card_id");
            sendRequest("/api/asset/delete_card/", {
                data: {
                    card_id: card_id
                },
                method: "post",
                dataType: "json",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.alert({
                            type: "error",
                            title: i18n("delete_failed"),
                            message: data.error,
                            hideCancel: true
                        });
                        return
                    }
                    $item.remove();
                    $("#bank_card_select .select-list-item[card_id=" + card_id + "]").remove();
                    var current_card_count = $("#bank_card_select .select-list-item").length - 1;
                    if (current_card_count < max_bank_card_count) {
                        $("#bank_card_select .card-list-add").show()
                    } else {
                        $("#bank_card_select .card-list-add").hide()
                    }
                    show_selected_card();
                    select_card_callback()
                }
            })
        };
        $(window).click(function() {
            $("#bank_card_select .select-list").hide()
        });
        $("#bank_card_select .selected, #bank_card_select .icon_expand").click(function(e) {
            e.stopPropagation();
            $("#bank_card_select .select-list").toggle()
        });
        $("#bank_card_select").delegate(".select-list-item", "click", function(e) {
            if ($(this).hasClass("card-list-add")) {
                var current_card_count = $("#card-list li").length - 1;
                if (current_card_count >= max_bank_card_count) {
                    Buff.alert({
                        type: "error",
                        title: i18n("card_limit_is_reached"),
                        message: i18n("pmost_can_only_be_bound") + max_bank_card_count + i18n("cardsp"),
                        hideCancel: true
                    })
                } else {
                    var callback = function(card_info) {
                        add_card(card_info);
                        select_card_callback()
                    };
                    show_bind_card_popup(realname, callback)
                }
            } else {
                $("#bank_card_select .select-list-item").removeClass("on");
                $(this).addClass("on");
                $("#bank_card_select .select-list").toggle();
                show_selected_card($(this));
                select_card_callback()
            }
        });
        show_selected_card();
        $("#bank_card_select").delegate(".Btn_delete", "click", function() {
            var ele = $(this).parent();
            Buff.alert({
                title: i18n("delete_confirmation"),
                message: i18n("sure_you_want_to_delete"),
                success: function() {
                    delete_card(ele)
                }
            })
        })
    };
    var init_zhima_cert = function(cert_callback) {
        if (!cert_callback) {
            cert_callback = function() {}
        }
        var zhima_input_error = input_error("j_popup_zhima");
        var zhima_input = {
            data: {},
            error_msg: "",
            show_error: true,
            add_text_error: function($item) {
                if (this.show_error) {
                    zhima_input_error.show(this.error_msg, $item)
                }
            },
            get: function() {
                zhima_input_error.clear_all();
                var $zhima_popup = $("#j_popup_zhima");
                var $realname = $zhima_popup.find("input[name=realname]");
                var realname = $realname.val().replace(/\s/, "");
                this.error_msg = check_realname(realname);
                if (this.error_msg) {
                    this.add_text_error($realname);
                    return undefined
                }
                this.data["realname"] = realname;
                var $id_card = $zhima_popup.find("input[name=id_card]");
                var id_card = $id_card.val().replace(/\s/, "");
                this.error_msg = check_id_card(id_card);
                if (this.error_msg) {
                    this.add_text_error($id_card);
                    return undefined
                }
                this.data["id_card"] = id_card;
                if (!$("#zhima-cert-allow-check").hasClass("on")) {
                    this.error_msg = i18n("please_agree_to_the_service");
                    this.add_text_error();
                    return undefined
                }
                return true
            }
        };
        var zhima_cert = function() {
            if (zhima_input.get() == undefined) {
                return
            }
            sendRequest("/api/asset/zhima_cert/", {
                data: zhima_input.data,
                method: "post",
                dataType: "json",
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        if (data.code == "Realname Certed") {
                            setTimeout("location.reload();", 2e3)
                        }
                        return
                    }
                    var cert_url = data.data["cert_url"];
                    if (!cert_url) {
                        Buff.toast(i18n("application_authentication_failure_please_contact"), {
                            type: "error"
                        });
                        return
                    }
                    if (getDeviceOS() != "web") {
                        location.href = cert_url;
                        return
                    }
                    $("#zhima-cert-qrcode").empty();
                    new QRCode(document.getElementById("zhima-cert-qrcode"),{
                        text: cert_url,
                        width: 200,
                        height: 200
                    });
                    $("#zhima-cert-qrcode").attr("title", "");
                    Popup.show("j_popup_zhima_cert_qrcode");
                    var zhima_cert_id = data.data["zhima_cert_id"];
                    var retry_limit = 60;
                    wait_query_handler = setInterval(function() {
                        retry_limit -= 1;
                        if (retry_limit < 0) {
                            clearInterval(wait_query_handler);
                            wait_query_handler = undefined;
                            console.debug("stop querying state.");
                            return
                        }
                        zhima_cert_query(zhima_cert_id)
                    }, 5e3)
                }
            })
        };
        var zhima_cert_query = function(zhima_cert_id) {
            sendRequest("/api/asset/zhima_cert/query/", {
                data: {
                    zhima_cert_id: zhima_cert_id
                },
                method: "get",
                dataType: "json",
                showLoading: false,
                success: function(data) {
                    if (data.data["state"] == 2) {
                        Buff.toast(i18n("the_authentication_is_successful"), {
                            type: "success"
                        });
                        cert_callback()
                    }
                }
            })
        };
        $("#change_to_card").unbind().bind("click", function() {
            Popup.hide();
            Popup.show("j_popup_card")
        });
        $("#j_popup_zhima .i_Btn_main").unbind().bind("click", function() {
            zhima_cert()
        });
        $("#zhima-cert-allow-check").unbind().bind("click", function() {
            if ($(this).hasClass("on")) {
                $(this).removeClass("on");
                $("#j_popup_zhima .i_Btn_main").addClass("i_Btn_disabled")
            } else {
                $(this).addClass("on");
                $("#j_popup_zhima .i_Btn_main").removeClass("i_Btn_disabled")
            }
            event.stopPropagation()
        })
    };
    var show_cert_popup = function(realname, cert_callback) {
        init_card_popup(realname, true, cert_callback);
        Popup.show("j_popup_card")
    };
    var show_bind_card_popup = function(realname, bind_card_callback) {
        init_card_popup(realname, false, bind_card_callback);
        Popup.show("j_popup_card")
    };
    var show_authcode_popup = function(config) {
        var mobile = config.mobile;
        var send_authcode_function = config.send_authcode_function;
        var verify_authcode_function = config.verify_authcode_function;
        var cancel_function = config.cancel_function;
        var content = config.content;
        var authcode_length = config.authcode_length || 6;
        var popup_id = config.popup_id || "j_popup_authcode";
        var $j_popup_authcode = $("#" + popup_id);
        var $authcode = $j_popup_authcode.find("input[name=authcode]");
        eval("var reg = /^\\d{" + authcode_length + "}$/;");
        $authcode.unbind("input").bind("input", function() {
            var authcode = $(this).val();
            if (reg.test(authcode)) {
                $j_popup_authcode.find("#verify_authcode").removeClass("i_Btn_disabled")
            } else {
                $j_popup_authcode.find("#verify_authcode").addClass("i_Btn_disabled")
            }
        });
        $j_popup_authcode.find("#resend_authcode").unbind("click").bind("click", function(event) {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            send_authcode_function(function() {
                countdown($j_popup_authcode.find("#resend_authcode"))
            }, true);
            event.stopPropagation()
        });
        $j_popup_authcode.find("#verify_authcode").unbind("click").bind("click", function(event) {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            var authcode = $authcode.val();
            if (!reg.test(authcode)) {
                Buff.toast(i18n("please_enter_the_verification_code"), {
                    type: "warning"
                });
                return
            }
            verify_authcode_function(authcode, function() {
                wait = wait == WAIT_TIME ? WAIT_TIME : 0;
                Popup.hide();
                countdown_handler = undefined;
                $j_popup_authcode.find("#verify_authcode").addClass("i_Btn_disabled");
                event.stopPropagation()
            })
        });
        $j_popup_authcode.find(".popup-close").unbind("click").bind("click", function() {
            wait = wait == WAIT_TIME ? WAIT_TIME : 0;
            Popup.hide();
            $j_popup_authcode.find("#verify_authcode").addClass("i_Btn_disabled");
            if (cancel_function) {
                cancel_function()
            }
        });
        $authcode.val("");
        if (content) {
            $j_popup_authcode.find(".popup-desc p:first").text(content)
        } else {
            $j_popup_authcode.find("#mobile").text(mobile)
        }
        Popup.show(popup_id);
        if (countdown_handler === undefined) {
            countdown($j_popup_authcode.find("#resend_authcode"))
        }
    };
    return {
        init_card_popup: init_card_popup,
        show_cert_popup: show_cert_popup,
        show_bind_card_popup: show_bind_card_popup,
        show_authcode_popup: show_authcode_popup,
        init_card_list: init_card_list,
        get_selected_card: get_selected_card,
        highlight_card: highlight_card,
        cancel_highlight_card: cancel_highlight_card
    }
}();
var Recharge = function() {
    var RECHARGE_MIN_AMOUNT = 5;
    var RECHARGE_MAX_AMOUNT = 2e4;
    var wait_recharge_handler;
    var EPAY_QUICK_PAY = 2;
    var ALIPAY_PAGE = 4;
    var PCREDIT_PAGE = 10;
    var PAYPAL_PAGE = 13;
    var CNP_PAGE = 14;
    var show_fee = function(amount, pay_method) {
        sendRequest("/api/asset/recharge/fee/", {
            method: "get",
            data: {
                amount: amount,
                pay_method: pay_method
            },
            showLoading: false,
            success: function(json_data) {
                var data = json_data.data;
                $("#actual_pay").html(formatPriceNormalYuan(data.amount, true));
                $("#total_fee").html(formatPriceNormalYuan(data.fee, true))
            }
        })
    };
    var recharge_info = {
        data: {},
        error_msg: "",
        get: function() {
            var error = false;
            this.error_msg = "";
            var amount = $("#amount_list").attr("value");
            if (amount == "custom" || amount === undefined || amount == "") {
                amount = parseFloat($("#amount_list input[type=text][name=amount]").val().replace(/[^0-9\.]/g, ""))
            } else {
                $("input[type=text][name=amount]").val("")
            }
            if (isNaN(amount)) {
                amount = 0
            }
            if (amount) {
                this.data["amount"] = amount
            } else {
                error = true;
                this.error_msg = i18n("please_enter_or_select_the");
                return undefined
            }
            var pay_method = $("#recharge_method li.on").attr("value");
            if (pay_method) {
                this.data["pay_method"] = parseInt(pay_method)
            } else {
                error = true;
                this.error_msg = i18n("please_select_recharge_way\n");
                return undefined
            }
            show_fee(this.data["amount"], this.data["pay_method"]);
            var need_card = false;
            if (pay_method == EPAY_QUICK_PAY) {
                need_card = true
            }
            if (need_card) {
                var selected_card = bindCard.get_selected_card();
                if (selected_card) {
                    this.data["card_id"] = selected_card.card_id;
                    this.data["mobile"] = selected_card.mobile
                } else {
                    error = true;
                    this.error_msg = i18n("please_select_the_card\n");
                    return undefined
                }
            }
            if (error) {
                return undefined
            }
            return true
        }
    };
    var enable_or_disable_recharge_button = function() {
        if (recharge_info.get() == undefined) {
            $("#send_recharge_authcode").addClass("i_Btn_disabled").removeClass("i_Btn_main");
            bindCard.cancel_highlight_card()
        } else {
            $("#send_recharge_authcode").removeClass("i_Btn_disabled").addClass("i_Btn_main");
            bindCard.highlight_card()
        }
    };
    var enable_or_disable_button = enable_or_disable_recharge_button;
    var get_recharge_log = function(current_page, event) {
        if (current_page == undefined) {
            current_page = 1
        }
        sendRequest("/api/asset/recharge_log/", {
            data: {
                page_num: current_page
            },
            method: "get",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    return
                }
                var recharge_logs = data.data;
                if (recharge_logs.length == 0) {
                    $("#recharge_logs .nodata").show()
                } else {
                    var $list_tb = $("#recharge_logs .list_tb");
                    $list_tb.find('tr:not(":first")').remove();
                    $list_tb.append(template_render("recharge_log_pat", {
                        recharge_logs: recharge_logs["items"]
                    }));
                    $list_tb.show()
                }
                recharge_logs.onPageClick = get_recharge_log;
                renderPagination(recharge_logs);
                check_confirming_order()
            },
            error: function() {}
        })
    };
    var timeout_handler;
    var check_confirming_order = function(check_recharge_id) {
        var url = "/api/asset/recharge_state_check/?";
        if (check_recharge_id != undefined) {
            url += "recharge_id=" + check_recharge_id
        } else {
            var $confirmimg_orders = $('#recharge_logs tr[state="CONFIRMING"]');
            if ($confirmimg_orders.length == 0) {
                return
            }
            var recharge_ids = [];
            $confirmimg_orders.each(function() {
                recharge_ids.push($(this).attr("recharge_id"))
            });
            url += "recharge_id=" + recharge_ids.join()
        }
        sendRequest(url, {
            method: "get",
            dataType: "json",
            showLoading: false,
            showError: false,
            success: function(data) {
                if (data.code == "OK") {
                    for (var recharge_id in data.data.items) {
                        show_brief_asset();
                        break
                    }
                    if (check_recharge_id && data.data.items.hasOwnProperty(check_recharge_id) && wait_recharge_handler) {
                        if (data.data.items[check_recharge_id].state[0] == "CONFIRMING") {
                            return
                        }
                        clearInterval(wait_recharge_handler);
                        wait_recharge_handler = undefined;
                        Popup.hide();
                        Buff.alert({
                            type: "success",
                            title: i18n("recharge_successful"),
                            message: i18n("recharge_yuan") + data.data.items[check_recharge_id].amount + i18n("the_current_balance_of_dollar") + data.data.cash_amount,
                            hideCancel: true
                        });
                        check_confirming_order()
                    }
                    for (var recharge_id in data.data.items) {
                        $("#recharge_logs tr[recharge_id=" + recharge_id + "]").replaceWith(template_render("recharge_log_pat", {
                            recharge_logs: [data.data.items[recharge_id]]
                        }))
                    }
                }
                if (check_recharge_id === undefined) {
                    timeout_handler = setTimeout(check_confirming_order, 5e3)
                }
            }
        })
    };
    var _check_recharge_data = function() {
        if (recharge_info.get() == undefined) {
            Buff.toast(recharge_info.error_msg);
            return
        }
        var recharge_data = recharge_info.data;
        var recharge_amount = recharge_data.amount;
        if (recharge_amount) {
            if (!$.isNumeric(recharge_amount)) {
                Buff.alert({
                    type: "error",
                    title: i18n("recharge_failed"),
                    message: i18n("the_amount_of_recharge_need"),
                    hideCancel: true
                });
                return
            }
            if (recharge_amount > RECHARGE_MAX_AMOUNT) {
                Buff.alert({
                    type: "error",
                    title: i18n("recharge_failed"),
                    message: i18n("the_maximum_allowable_amount_of") + RECHARGE_MAX_AMOUNT + i18n("yuan"),
                    hideCancel: true
                });
                return
            }
            if (recharge_amount < RECHARGE_MIN_AMOUNT) {
                Buff.alert({
                    type: "error",
                    title: i18n("recharge_failed"),
                    message: i18n("the_minimum_allowable_amount_of") + RECHARGE_MIN_AMOUNT + i18n("yuan"),
                    hideCancel: true
                });
                return
            }
        }
        return recharge_data
    };
    var recharge_preview = function() {
        var to_recharge = function(pay_method) {
            if (pay_method == EPAY_QUICK_PAY) {
                send_recharge_authcode()
            } else if ([CNP_PAGE, PAYPAL_PAGE, ALIPAY_PAGE, PCREDIT_PAGE].indexOf(pay_method) != -1) {
                alipay_recharge()
            }
        };
        var recharge_data = _check_recharge_data();
        if (recharge_data == undefined) {
            return
        }
        sendRequest("/api/asset/recharge/preview/", {
            data: recharge_data,
            method: "POST",
            dataType: "json",
            ignoreCode: ["Recharge Repeat"],
            success: function(data) {
                if (data.code != "OK") {
                    var ce = data.confirm_entry;
                    if (ce) {
                        Buff.alert({
                            type: "warning",
                            title: data.confirm_entry.title,
                            message: data.confirm_entry.message,
                            cancelText: data.confirm_entry.button_cancel,
                            confirmText: data.confirm_entry.button_noted,
                            success: function() {
                                to_recharge(recharge_data.pay_method)
                            }
                        })
                    } else {
                        Buff.toast(data.error)
                    }
                    return
                }
                to_recharge(recharge_data.pay_method)
            }
        })
    };
    var recharge_id = undefined;
    var send_recharge_authcode = function(after_send_authcode_function, retry) {
        var recharge_data = _check_recharge_data();
        if (recharge_data == undefined) {
            return
        }
        var show_authcode_popup = function() {
            bindCard.show_authcode_popup({
                mobile: recharge_data.mobile,
                send_authcode_function: send_recharge_authcode,
                verify_authcode_function: recharge
            })
        };
        if (!retry) {
            recharge_id = undefined
        }
        sendRequest("/api/asset/recharge/", {
            data: recharge_data,
            method: "post",
            dataType: "json",
            success: function(data) {
                if (data.code != "OK") {
                    Buff.alert({
                        type: "error",
                        title: i18n("send_a_verification_code_failed"),
                        message: data.code == "Epay Response Error" ? data.error || i18n("the_system_is_busy_please") : data.error,
                        hideCancel: true
                    });
                    return
                }
                if (recharge_id === undefined) {
                    show_authcode_popup()
                }
                recharge_id = data.data.recharge_id;
                if (after_send_authcode_function) {
                    after_send_authcode_function()
                }
            }
        })
    };
    var recharge = function(authcode, after_verify_function) {
        if (!recharge_id || !authcode) {
            Buff.toast(i18n("please_get_a_verification_code"));
            return
        }
        sendRequest("/api/asset/recharge_verify/", {
            data: {
                authcode: authcode,
                recharge_id: recharge_id
            },
            method: "post",
            dataType: "json",
            success: function(data) {
                if (data.code != "OK") {
                    Buff.alert({
                        type: "error",
                        title: "支付失败",
                        message: data.code == "Epay Response Error" ? data.error || i18n("the_system_is_busy_you") : data.error,
                        hideCancel: true
                    });
                    return
                }
                $("#amount_list li.on").removeClass("on");
                $("input[type=text][name=amount]").val("");
                $("#recharge_amount").text("");
                var check_recharge_id = recharge_id;
                recharge_id = undefined;
                enable_or_disable_button();
                if (after_verify_function) {
                    after_verify_function()
                }
                get_recharge_log();
                var popup_recharge_wait = Buff.alert({
                    title: i18n("being_prepaid_in"),
                    message: i18n("please_be_patient"),
                    hideCancel: true,
                    hideConfirm: true
                });
                if (timeout_handler) {
                    clearTimeout(timeout_handler)
                }
                var wait = 0;
                wait_recharge_handler = setInterval(function() {
                    wait += 1;
                    if (wait <= 10) {
                        $("#" + popup_recharge_wait + " p").text(i18n("please_wait_patiently_have_been") + wait + "s...");
                        check_confirming_order(check_recharge_id)
                    } else {
                        clearInterval(wait_recharge_handler);
                        wait_recharge_handler = undefined;
                        Popup.hide();
                        Buff.alert({
                            title: i18n("the_system_is_busy"),
                            message: i18n("you_can_recharge_in_a"),
                            hideCancel: true
                        });
                        check_confirming_order()
                    }
                }, 1e3)
            }
        })
    };
    var alipay_recharge = function() {
        var recharge_data = _check_recharge_data();
        if (recharge_data == undefined) {
            return
        }
        var url = "/api/asset/recharge_alipay_page/";
        if (recharge_data.pay_method == PCREDIT_PAGE) {
            url = "/api/asset/recharge_pcredit_page/"
        }
        if (recharge_data.pay_method == PAYPAL_PAGE) {
            url = "/api/asset/recharge_paypal_page/"
        }
        if (recharge_data.pay_method == CNP_PAGE) {
            url = "/api/asset/recharge_cnp_page/"
        }
        sendRequest(url, {
            data: recharge_data,
            method: "post",
            dataType: "json",
            timeout: 3e4,
            success: function(data) {
                if (data.code != "OK") {
                    Buff.alert({
                        type: "error",
                        title: i18n("recharge_failed"),
                        message: data.code == "Epay Response Error" ? data.error || i18n("the_system_is_busy_please") : data.error,
                        hideCancel: true
                    });
                    return
                }
                location.href = data.data.redirect_url
            }
        })
    };
    var init = function(args) {
        RECHARGE_MAX_AMOUNT = args.amount_max;
        RECHARGE_MIN_AMOUNT = args.amount_min;
        var amount_item = "input[type=text][name=amount]";
        $("#amount_list").bind("change", function() {
            var selected_value = $(this).find("span.on").attr("value");
            if (selected_value != undefined && selected_value != "custom") {
                $("#amount_list").attr("value", "custom");
                $(amount_item).val(selected_value)
            }
            enable_or_disable_button()
        });
        var recharge_amount_more = false;
        $(amount_item).bind("change paste keyup", function(event) {
            if (parseFloat($(this).val()) > RECHARGE_MAX_AMOUNT) {
                if (!recharge_amount_more) {
                    $(this).unbind("keypress").bind("keypress", function() {
                        return false
                    });
                    $(this).val(RECHARGE_MAX_AMOUNT);
                    recharge_amount_more = true
                }
            } else if (recharge_amount_more) {
                var amount = parseFloat($(this).val());
                if (isNaN(amount) || isTextSelected($(amount_item)[0]) || amount < RECHARGE_MAX_AMOUNT) {
                    $(this).unbind("keypress");
                    Buff.pricePatten(amount_item);
                    recharge_amount_more = false
                }
            }
            enable_or_disable_button()
        }).bind("mouseover", function(event) {
            var $item = $("#amount_list span.on");
            if ($item.attr("value") == "custom") {
                return false
            }
            $item.removeClass("on")
        });
        Buff.pricePatten(amount_item);
        $(amount_item).focus().click();
        $("#recharge_method li").click(function() {
            var pay_method = parseInt($(this).attr("value"));
            if (!pay_method) {
                Buff.toast($(this).attr("title"), {
                    type: "warning"
                });
                return
            }
            $(this).parent("ul").find("li").removeClass("on");
            $(this).addClass("on");
            if (pay_method == EPAY_QUICK_PAY) {
                $("#recharge_bank_cards").show();
                $("#notice-alipay").hide();
                $("#notice-pcredit").hide();
                $("#notice-bank").show();
                $("#service_fee").hide()
            } else {
                $("#recharge_bank_cards").hide();
                if (pay_method == ALIPAY_PAGE) {
                    $("#notice-alipay").show();
                    $("#notice-pcredit").hide();
                    $("#service_fee").hide()
                } else if (pay_method == PCREDIT_PAGE) {
                    $("#notice-pcredit").show();
                    $("#notice-alipay").hide();
                    $("#service_fee").show()
                }
                $("#notice-bank").hide()
            }
            enable_or_disable_button()
        });
        $("#recharge_method li:first").click();
        $("#send_recharge_authcode").click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return false
            }
            recharge_preview()
        });
        get_recharge_log();
        enable_or_disable_button();
        bindCard.init_card_list(args.realname, args.max_card_count, enable_or_disable_button)
    };
    return {
        init: init,
        enable_or_disable_button: enable_or_disable_button
    }
}();
var Withdraw = function() {
    var WITHDRAW_MIN_AMOUNT = 10;
    var WITHDRAW_MAX_AMOUNT = 5e4;
    var available_amount = {};
    var _realname = null;
    var _alipay_sms_countdown = 0;
    var return_to_url = null;
    var auto_highlight_alipay = false;
    var withdraw_fee = null;
    var remain_withdraw_counts = null;
    var show_fee = function(alipay_amount, epay_amount, cdkey_id) {
        var _show = function(alipay_real_amount, epay_real_amount, total_fee) {
            var $alipay_received = $("#alipay_received");
            if (alipay_real_amount > 0) {
                $alipay_received.find("span").html(formatPriceNormalYuan(alipay_real_amount, true));
                $alipay_received.css("visibility", "visible")
            } else {
                $alipay_received.css("visibility", "hidden")
            }
            var $epay_received = $("#epay_received");
            if (epay_real_amount > 0) {
                $epay_received.find("span").html(formatPriceNormalYuan(epay_real_amount, true));
                $epay_received.css("visibility", "visible")
            } else {
                $epay_received.css("visibility", "hidden")
            }
            $("#total_fee").html(formatPriceNormalYuan(total_fee, true))
        };
        if (alipay_amount > 0 && alipay_amount < WITHDRAW_MIN_AMOUNT || epay_amount > 0 && epay_amount < WITHDRAW_MIN_AMOUNT) {
            return
        }
        sendRequest("/api/asset/withdraw_together/fee/", {
            method: "get",
            data: {
                epay_amount: epay_amount,
                alipay_amount: alipay_amount,
                cdkey_id: cdkey_id
            },
            showLoading: false,
            success: function(json_data) {
                var data = json_data.data;
                _show(data.alipay.real_amount, data.epay.real_amount, data.total.fee);
                withdraw_fee = data
            }
        })
    };
    var check_withdraw_info = function(data) {
        if (data === undefined) {
            data = _get_withdraw_info(true)
        }
        var epay_amount = data.epay_amount;
        var alipay_amount = data.alipay_amount;
        var epay_error = true;
        var alipay_error = true;
        var withdraw_with_alipay = false;
        var withdraw_with_epay = false;
        var $epay_received = $("#epay_received");
        var $epay_amount_error = $("#epay_amount_error");
        var $alipay_received = $("#alipay_received");
        var $alipay_amount_error = $("#alipay_amount_error");
        if (epay_amount > 0 && epay_amount < WITHDRAW_MIN_AMOUNT) {
            $epay_amount_error.text(i18n("less_than") + WITHDRAW_MIN_AMOUNT + i18n("yuan"))
        } else if (epay_amount > available_amount.epay_amount) {
            $epay_amount_error.text(i18n("greater_than_the_extraction_amount"))
        } else {
            epay_error = false
        }
        if (epay_error) {
            bindCard.cancel_highlight_card();
            $epay_received.css("visibility", "hidden");
            $epay_received.parent().removeClass("on");
            $epay_amount_error.css("visibility", "visible")
        } else {
            $epay_amount_error.css("visibility", "hidden");
            if (epay_amount > 0) {
                $epay_received.parent().addClass("on");
                bindCard.highlight_card();
                withdraw_with_epay = true
            } else {
                $epay_received.parent().removeClass("on");
                bindCard.cancel_highlight_card()
            }
        }
        if (alipay_amount > 0 && alipay_amount < WITHDRAW_MIN_AMOUNT) {
            $alipay_amount_error.text(i18n("less_than") + WITHDRAW_MIN_AMOUNT + i18n("yuan"))
        } else if (alipay_amount > available_amount.alipay_amount) {
            $alipay_amount_error.text(i18n("greater_than_the_extraction_amount"))
        } else {
            alipay_error = false
        }
        if (alipay_error) {
            cancel_highlight_alipay();
            $alipay_received.css("visibility", "hidden");
            $alipay_received.parent().removeClass("on");
            $alipay_amount_error.css("visibility", "visible")
        } else {
            $alipay_amount_error.css("visibility", "hidden");
            if (alipay_amount > 0) {
                $alipay_received.parent().addClass("on");
                highlight_alipay();
                withdraw_with_alipay = true
            } else {
                $alipay_received.parent().removeClass("on");
                cancel_highlight_alipay()
            }
        }
        if (!alipay_error && !epay_error) {
            show_fee(data["alipay_amount"], data["epay_amount"], data["cdkey_id"])
        }
        var error = false;
        if (alipay_amount == 0 && epay_amount == 0 || alipay_error || epay_error) {
            error = true
        } else if (alipay_amount > 0 && (!data["alipay_account"] && !data["alipay_account_id"])) {
            error = true
        } else if (epay_amount > 0 && !data["card_id"]) {
            error = true
        }
        if (error) {
            $("#withdraw_btn").removeClass("i_Btn_main").addClass("i_Btn_disabled")
        } else {
            $("#withdraw_btn").removeClass("i_Btn_disabled").addClass("i_Btn_main")
        }
        if (withdraw_with_alipay && withdraw_with_epay) {
            $("#remain_withdraw_count_today_span").show();
            $("#remain_withdraw_count_today").html(i18n("remain_withdrawal_count_today") + "&nbsp;" + remain_withdraw_counts["together"])
        } else if (withdraw_with_alipay) {
            $("#remain_withdraw_count_today_span").show();
            $("#remain_withdraw_count_today").html(i18n("remain_withdrawal_count_today") + "&nbsp;" + remain_withdraw_counts["alipay"])
        } else if (withdraw_with_epay) {
            $("#remain_withdraw_count_today_span").show();
            $("#remain_withdraw_count_today").html(i18n("remain_withdrawal_count_today") + "&nbsp;" + remain_withdraw_counts["epay"])
        } else {
            $("#remain_withdraw_count_today_span").hide();
            $("#remain_withdraw_count_today").html("")
        }
        return !error
    };
    var _get_withdraw_info = function(for_check, for_data) {
        var data = {};
        var alipay_amount = 0;
        var epay_amount = 0;
        $("input[name=alipay_amount],input[name=epay_amount]").each(function() {
            var amount = $(this).val();
            amount = amount.replace(/[^0-9\.]/g, "");
            if (amount) {
                amount = parseFloat(amount)
            } else {
                amount = 0
            }
            if ($(this).attr("name") == "alipay_amount") {
                alipay_amount = amount
            } else {
                epay_amount = amount
            }
        });
        data["alipay_amount"] = alipay_amount;
        data["epay_amount"] = epay_amount;
        var selected_card = bindCard.get_selected_card();
        if (selected_card) {
            data["card_id"] = selected_card.card_id
        }
        var selected_alipay = get_selected_alipay();
        if (selected_alipay) {
            data["alipay_account"] = selected_alipay.account;
            data["alipay_account_id"] = selected_alipay.account_id
        }
        var selected_coupon = get_selected_coupon();
        if (selected_coupon) {
            data["cdkey_id"] = selected_coupon["cdkey_id"]
        }
        if (for_check) {
            return data
        }
        if (for_data) {
            if (check_withdraw_info(data)) {
                return data
            }
            return undefined
        }
        setTimeout(check_withdraw_info, 200)
    };
    var clear_withdraw_info = function() {
        $("input[name=alipay_amount],input[name=epay_amount]").each(function() {
            $(this).val("")
        });
        check_withdraw_info()
    };
    var get_withdraw_data = function() {
        return _get_withdraw_info(false, true)
    };
    var enable_or_disable_withdraw_button = function() {
        _get_withdraw_info(false, false)
    };
    var enable_or_disable_button = enable_or_disable_withdraw_button;
    var withdraw_amount_check = function(withdraw_data) {
        if (withdraw_data.epay_amount > 0 && withdraw_data.epay_amount < WITHDRAW_MIN_AMOUNT || withdraw_data.alipay_amount > 0 && withdraw_data.alipay_amount < WITHDRAW_MIN_AMOUNT) {
            Buff.alert({
                type: "error",
                title: i18n("withdrawal_failure"),
                message: i18n("withdrawal_minimum_amount_is") + WITHDRAW_MIN_AMOUNT + i18n("yuan"),
                hideCancel: true
            });
            return false
        }
        if (withdraw_data.epay_amount + withdraw_data.alipay_amount > WITHDRAW_MAX_AMOUNT) {
            Buff.alert({
                type: "error",
                title: i18n("withdrawal_failure"),
                message: i18n("withdraw_the_maximum_amount_of") + WITHDRAW_MAX_AMOUNT + i18n("yuan"),
                hideCancel: true
            });
            return false
        }
        return true
    };
    var withdraw_authcode_sended = false;
    var send_withdraw_authcode = function(after_send_authcode_function, retry) {
        var withdraw_data = get_withdraw_data();
        var show_authcode_popup = function(mobile) {
            bindCard.show_authcode_popup({
                send_authcode_function: send_withdraw_authcode,
                verify_authcode_function: withdraw_verify,
                content: i18n("to_guarantee_your_safety_of") + mobile + i18n("receive_sms_verification_code"),
                authcode_length: 4
            })
        };
        if (!retry) {
            withdraw_authcode_sended = false
        }
        sendRequest("/api/asset/withdraw_together/authcode/", {
            data: withdraw_data,
            method: "post",
            dataType: "json",
            success: function(data) {
                if (data.code != "OK") {
                    if (data.code == "Withdraw Alipay Not Enough") {
                        Buff.alert({
                            type: "error",
                            title: i18n("the_lack_of_balance"),
                            message: i18n("the_account_can_be_withdrawal"),
                            hideCancel: true
                        })
                    } else if (data.code == "Withdraw Cash Not Enough") {
                        Buff.alert({
                            type: "error",
                            title: i18n("the_lack_of_balance"),
                            message: i18n("account_can_be_withdraw_the"),
                            hideCancel: true
                        })
                    } else {
                        Buff.alert({
                            type: "error",
                            title: i18n("send_a_verification_code_failed"),
                            message: data.code == "Epay Response Error" ? data.error || i18n("the_system_is_busy_please") : data.error,
                            hideCancel: true
                        })
                    }
                    return
                }
                if (!withdraw_authcode_sended) {
                    show_authcode_popup(data.data.mobile)
                }
                withdraw_authcode_sended = true;
                if (after_send_authcode_function) {
                    after_send_authcode_function()
                }
            }
        })
    };
    var withdraw_verify = function(authcode, after_verify_function) {
        var withdraw_data = get_withdraw_data();
        withdraw_data["authcode"] = authcode;
        sendRequest("/api/asset/withdraw_together/verify/", {
            data: withdraw_data,
            method: "post",
            dataType: "json",
            success: function(data) {
                if (data.code == "Withdraw Need Authcode") {
                    send_withdraw_authcode();
                    return
                }
                if (data.code != "OK") {
                    Buff.alert({
                        type: "error",
                        title: i18n("withdrawal_failure"),
                        message: data.code == "Epay Response Error" ? data.error || i18n("the_system_is_busyplease_try") : data.error,
                        hideCancel: true
                    });
                    return
                }
                clear_withdraw_info();
                if (after_verify_function) {
                    after_verify_function()
                }
                get_withdraw_log();
                show_brief_asset();
                Buff.alert({
                    title: i18n("withdrawal_has_been_filed"),
                    message: i18n("withdraw_cash_price_of_dollar") + (withdraw_data.alipay_amount + withdraw_data.epay_amount).toFixed(2) + i18n("is_being_processed_you_can"),
                    hideCancel: true,
                    success: function() {
                        document.location.reload()
                    }
                })
            }
        })
    };
    var get_withdraw_log = function(current_page, event) {
        if (current_page == undefined) {
            current_page = 1
        }
        sendRequest("/api/asset/withdraw_log/", {
            data: {
                page_num: current_page
            },
            method: "get",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    return
                }
                var withdraw_logs = data.data;
                if (withdraw_logs.length == 0) {
                    $("#withdraw_logs .nodata").show()
                } else {
                    var $list_tb = $("#withdraw_logs .list_tb");
                    $list_tb.find('tr:not(":first")').remove();
                    $list_tb.append(template_render("withdraw_log_pat", {
                        withdraw_logs: withdraw_logs["items"]
                    }));
                    $list_tb.show()
                }
                withdraw_logs.onPageClick = get_withdraw_log;
                renderPagination(withdraw_logs);
                check_confirming_order()
            },
            error: function() {}
        })
    };
    var check_confirming_order = function() {
        var $confirmimg_orders = $('#withdraw_logs tr[state="CONFIRM"], #withdraw_logs tr[state="CREATED"]');
        if ($confirmimg_orders.length == 0) {
            return
        }
        var url = "/api/asset/withdraw_state_check/?";
        var withdraw_ids = [];
        $confirmimg_orders.each(function() {
            withdraw_ids.push($(this).attr("withdraw_id"))
        });
        url += "withdraw_id=" + withdraw_ids.join();
        sendRequest(url, {
            method: "get",
            dataType: "json",
            showLoading: false,
            showError: false,
            success: function(data) {
                if (data.code != "OK") {
                    setTimeout(check_confirming_order, 3e4);
                    return
                }
                for (var withdraw_id in data.data.items) {
                    $("#withdraw_logs tr[withdraw_id=" + withdraw_id + "]").replaceWith(template_render("withdraw_log_pat", {
                        withdraw_logs: [data.data.items[withdraw_id]]
                    }))
                }
                setTimeout(check_confirming_order, 3e4)
            }
        })
    };
    var highlight_alipay = function() {
        auto_highlight_alipay = true;
        var $selected = $("#alipay_account_select .selected");
        if ($selected.find(".bank-name").length > 0) {
            $selected.addClass("on")
        }
    };
    var cancel_highlight_alipay = function() {
        auto_highlight_alipay = false;
        $("#alipay_account_select .selected").removeClass("on")
    };
    var get_selected_alipay = function() {
        var $selected_card_item = $("#alipay_account_select .select-list-item.on");
        if ($selected_card_item.length > 0) {
            var account = $selected_card_item.attr("account");
            var account_id = $selected_card_item.attr("account_id");
            return {
                account: account,
                account_id: account_id
            }
        }
    };
    var init_alipay_accounts = function() {
        var show_selected_alipay = function(selected_alipay) {
            if (!selected_alipay) {
                if ($("#alipay_account_select .select-list-item").hasClass("on")) {
                    selected_alipay = $("#alipay_account_select .select-list-item.on")
                } else {
                    selected_alipay = $("#alipay_account_select .select-list-item").first()
                }
            }
            if (!selected_alipay || selected_alipay.hasClass("card-list-add")) {
                return
            }
            var account = selected_alipay.attr("account");
            var account_id = selected_alipay.attr("account_id");
            var $target = $('<i class="icon icon_select_alipay_small"></i><span class="bank-name">' + account + "</span>");
            var $selected = $("#alipay_account_select .selected");
            $selected.html($target);
            if (auto_highlight_alipay) {
                $selected.addClass("on")
            }
            if (!selected_alipay.hasClass("card-list-add")) {
                selected_alipay.siblings().removeClass("on");
                selected_alipay.addClass("on")
            }
            enable_or_disable_button()
        };
        $(window).click(function() {
            $("#alipay_account_select .select-list").hide()
        });
        $("#alipay_account_select .selected, #alipay_account_select .icon_expand").click(function(e) {
            e.stopPropagation();
            $("#alipay_account_select .select-list").toggle()
        });
        $("#alipay_account_select").delegate(".select-list-item", "click", function(e) {
            if ($(this).hasClass("card-list-add")) {
                Popup.show("j_popup_bind_alipay_account")
            } else {
                $("#alipay_account_select .select-list").toggle();
                show_selected_alipay($(this));
                enable_or_disable_button()
            }
        });
        show_selected_alipay();
        var $div = $('<div class="select-list-item"></div>');
        var $icon = $('<i class="icon icon_select_alipay_small"></i>');
        var $account = $('<span class="bank-name"></span>');
        $("#bind_alipay_account_verify_btn").click(function() {
            var $input = $("#j_popup_bind_alipay_account input[name=alipay_account]");
            var alipay_account = $input.val().trim();
            if (!alipay_account) {
                $input.parent().addClass("i_Text_error");
                return
            }
            $input.parent().removeClass("i_Text_error");
            $input.val("");
            $account.text(alipay_account);
            $div.attr("account", alipay_account);
            $div.empty();
            $div.append($icon).append($account);
            $("#alipay_account_select .card-list-add").before($div);
            show_selected_alipay($div);
            $div.hide();
            Popup.hide()
        })
    };
    var get_selected_coupon = function() {
        var $selected = $("#coupon_select .select-list-item.on");
        if ($selected.length > 0) {
            return {
                cdkey_id: $selected.attr("cdkey_id")
            }
        }
    };
    var init_coupon = function() {
        sendRequest("/api/activity/coupon/my/?coupon_type=withdraw&state=unuse&page_size=15", {
            method: "get",
            dataType: "json",
            showLoading: false,
            showError: false,
            success: function(data) {
                var coupons = [];
                if (data.code == "OK") {
                    coupons = data.data.items
                }
                $("#coupon_select .select-list").append(template_render("coupons_pat", {
                    coupons: coupons
                }));
                $(window).click(function() {
                    $("#coupon_select .select-list").hide()
                });
                $("#coupon_select .selected, #coupon_select .icon_expand").click(function(e) {
                    e.stopPropagation();
                    $("#coupon_select .select-list").toggle()
                });
                $("#coupon_select").delegate(".select-list-item", "click", function(e) {
                    if ($(this).hasClass("scope-none")) {
                        return
                    }
                    if ($(this).find(".pay-tip").length > 0) {
                        $(this).find(".pay-tip").remove();
                        $(this).removeClass("on");
                        $("#coupon_select .selected .coupon-name").addClass("c_Gray").text(i18n("please_select_from_the_available"))
                    } else {
                        $(this).siblings().each(function() {
                            $(this).find(".pay-tip").remove();
                            $(this).removeClass("on")
                        });
                        $(this).append($('<span class="pay-tip c_Blue f_12px">' + i18n("has_been_used") + "</span>"));
                        $(this).addClass("on");
                        $("#coupon_select .selected .coupon-name").removeClass("c_Gray").text($(this).find(".coupon-name").text());
                        $("#coupon_select .select-list").toggle()
                    }
                    check_withdraw_info()
                })
            }
        })
    };
    var init = function(args) {
        WITHDRAW_MIN_AMOUNT = args.withdraw_min_amount;
        WITHDRAW_MAX_AMOUNT = args.withdraw_max_amount;
        available_amount = {
            alipay_amount: args.alipay_amount,
            epay_amount: args.epay_amount
        };
        _realname = args.realname || {};
        remain_withdraw_counts = args.remain_withdraw_counts || {};
        var amount_item = "input[name=alipay_amount], input[name=epay_amount]";
        $(amount_item).each(function() {
            var withdraw_amount_more = false;
            $(this).bind("change paste keyup", function(event) {
                if (parseFloat($(this).val()) > WITHDRAW_MAX_AMOUNT) {
                    if (!withdraw_amount_more) {
                        $(this).unbind("keypress").bind("keypress", function() {
                            return false
                        });
                        $(this).val(WITHDRAW_MAX_AMOUNT);
                        withdraw_amount_more = true
                    }
                } else if (withdraw_amount_more) {
                    var amount = parseFloat($(this).val());
                    if (isNaN(amount) || isTextSelected($(amount_item)[0]) || amount < WITHDRAW_MAX_AMOUNT) {
                        $(this).unbind("keypress");
                        Buff.pricePatten(amount_item);
                        withdraw_amount_more = false
                    }
                }
                enable_or_disable_button()
            })
        });
        Buff.pricePatten(amount_item);
        $(document).on("input", "input", function() {
            $(this).removeClass("i_Text_error")
        });
        init_alipay_accounts();
        init_coupon();
        get_withdraw_log();
        $("#withdraw_btn").click(function() {
            var withdraw_data = get_withdraw_data();
            if (withdraw_data == undefined || !withdraw_amount_check(withdraw_data)) {
                return
            }
            var send = function() {
                if (args.withdraw_need_authcode) {
                    send_withdraw_authcode()
                } else {
                    withdraw_verify()
                }
            };
            if (withdraw_fee) {
                var amounts = [withdraw_fee.total.amount, withdraw_fee.total.fee, withdraw_fee.alipay.real_amount, withdraw_fee.epay.real_amount];
                $("#j_withdraw_confirm .popup-desc strong").each(function(index) {
                    $(this).text(amounts[index])
                });
                $("#j_withdraw_confirm .i_Btn_main").unbind().bind("click", function() {
                    send();
                    Popup.hide()
                });
                Popup.show("j_withdraw_confirm")
            } else {
                send()
            }
        });
        bindCard.init_card_list(_realname, args.max_card_count, enable_or_disable_button);
        if ($.isEmptyObject(_realname)) {
            $(".card-list-add").click(function() {
                bindCard.show_cert_popup(null, function() {
                    document.location.reload()
                })
            })
        }
    };
    return {
        init: init,
        enable_or_disable_button: enable_or_disable_button
    }
}();
var Message = function() {
    var trade_message_format = function(message) {
        if (message.template_type == 103 || message.template_type == 107) {
            message.content = message.content.replace(/(.*)\[(.*)\](.*)/, "$1" + '<a href="/market/backpack?game=' + message.game + '" style="text-decoration: underline;">$2</a>$3')
        }
        if (message.template_type == 101) {
            message.content = message.content.replace(/(.*)\[(.*)\](.*)/, "$1" + '<a href="/market/sell_order/to_deliver?game=' + message.game + '" style="text-decoration: underline;">$2</a>$3')
        }
        if (message.template_type == 104 || message.template_type == 108 || message.template_type == 111 || message.template_type == 112 || message.template_type == 115 || message.template_type == 151 || message.template_type == 117 || message.template_type == 118 || message.template_type == 122 || message.template_type == 125 || message.template_type == 127 || message.template_type == 133) {
            message.content = message.content.replace(/(.*)\[\[sell_order_history\](.*)\[(.*)\]\](.*)/, "$1" + '<a href="/market/sell_order/history?game=' + message.game + "&search=$2" + '"style="text-decoration: underline;">$3</a>$4')
        }
        if (message.template_type == 104 || message.template_type == 105 || message.template_type == 109 || message.template_type == 114 || message.template_type == 125 || message.template_type == 126 || message.template_type == 130 || message.template_type == 131 || message.template_type == 132) {
            message.content = message.content.replace(/(.*)\[\[buy_order_history\](.*)\[(.*)\]\](.*)/, "$1" + '<a href="/market/buy_order/history?game=' + message.game + "&search=$2" + '"style="text-decoration: underline;">$3</a>$4')
        }
        if (message.template_type == 106) {
            message.content = message.content.replace(/(.*)\[\[buy_order_supplied\](.*)\[(.*)\]\](.*)/, "$1" + '<a href="/market/buy_order/supplied?game=' + message.game + "&buy_order_id=$2" + '"style="text-decoration: underline;">$3</a>$4')
        }
        if (message.template_type == 116) {
            message.content = message.content.replace(/(.*)\[(.*)\](.*)/, "$1" + '<a href="/market/steam_inventory?game=' + message.game + '" style="text-decoration: underline;">$2</a>$3')
        }
        if (message.template_type == 119 || message.template_type == 123) {
            message.content = message.content.replace(/(.*)\[\[goods_selling\](.*)\[(.*)\]\](.*)/, '$1<a href="/goods/$2#tab=selling" style="text-decoration: underline;">$3</a>$4');
            message.content = message.content.replace(/(.*)\[\[goods_buying\](.*)\[(.*)\]\](.*)/, '$1<a href="/goods/$2#tab=buying" style="text-decoration: underline;">$3</a>$4')
        }
        if (message.template_type == 120) {
            message.content = message.content.replace(/(.*)\[(.*)\](.*)/, "$1" + '<a href="/market/sell_order/received_bargain?game=' + message.game + '" style="text-decoration: underline;">$2</a>$3')
        }
        if (message.template_type == 121) {
            message.content = message.content.replace(/(.*)\[(.*)\](.*)/, "$1" + '<a href="/market/buy_order/to_receive?game=' + message.game + '" style="text-decoration: underline;">$2</a>$3')
        }
        if (message.template_type == 124) {
            message.content = message.content.replace(/(.*)\[(.*)\](.*)/, "$1" + '<a href="/market/buy_order/sent_bargain?game=' + message.game + '" style="text-decoration: underline;">$2</a>$3')
        }
        if (message.template_type == 128) {
            message.content = message.content.replace(/(.*)\[(.*)\](.*)/, "$1" + '<a href="/user-center/bookmark/sell_order?game=' + message.game + '" style="text-decoration: underline;">$2</a>$3')
        }
        return message.content
    };
    var system_message_format = function(message) {
        message.content = message.content.replace(/(.*)\[\[user_backpack\](.*)\[(.*)\]\](.*)/, "$1" + '<a href="/market/backpack?game=' + "$2" + '">$3</a>$4');
        message.content = message.content.replace(/(.*)\[\[market_preview\](.*),(.*)\[(.*)\]\](.*)/, "$1" + '<a href="/goods/' + "$3" + '#tab=user-preview">$4</a>$5');
        message.content = message.content.replace(/(.*)\[\[settings_api_key\](.*)\](.*)/, '$1<a href="/user-center/profile#steam_api_key">$2</a>$3');
        message.content = message.content.replace(/(.*)\[\[bind_card\](.*)\](.*)/, '$1<a href="/user-center/asset/withdraw/">$2</a>$3');
        message.content = message.content.replace(/(.*)\[\[device_management\](.*)\](.*)/, "$1$2$3");
        message.content = message.content.replace(/(.*)\[\[my_coupon\]\[(.*)\](.*)\](.*)/, '$1<a href="/user-center/coupon/$2">$3</a>$4');
        return message.content
    };
    var get_message = function(current_page) {
        if (current_page == undefined) {
            current_page = 1
        }
        var message_type = $("#j_mail-tab .on").attr("message_type");
        sendRequest("/api/message/messages", {
            data: {
                page_num: current_page,
                type: message_type
            },
            method: "get",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    alert(data.error);
                    return
                }
                var messages = data.data;
                var message_item = "";
                var pat_name = "";
                if (message_type == "trade") {
                    message_item = "#trade_message";
                    pat_name = "trade_message_pat"
                } else if (message_type == "system") {
                    message_item = "#system_message";
                    pat_name = "system_message_pat"
                }
                $(message_item + " table tr:not(:first)").remove();
                var message_html = "";
                if (messages.items.length == 0) {
                    $(message_item + " table").hide();
                    $(message_item + " .nodata").show()
                } else {
                    message_html = template_render(pat_name, {
                        messages: messages.items
                    });
                    $(message_item + " .nodata").hide();
                    $(message_item + " table").append(message_html).show()
                }
                messages.pager_name = message_item + " .pager";
                messages.onPageClick = get_message;
                renderPagination(messages)
            }
        })
    };
    var init = function() {
        template.defaults.imports.trade_message_format = trade_message_format;
        template.defaults.imports.system_message_format = system_message_format;
        var query_data = getParams(window.location.search.substring(1));
        if (query_data.type == "system") {
            $("#j_mail-tab li[message_type=system]").addClass("on");
            $("#system_message").show()
        } else {
            $("#j_mail-tab li[message_type=trade]").addClass("on");
            $("#trade_message").show()
        }
        get_message();
        $("#system_message").delegate(".msg-folder-handler", "click", function() {
            $(this).toggleClass("on");
            var index = $("#system_message .msg-folder-handler").index(this);
            $("#system_message .msg-folder").eq(index).toggle()
        });
        gameNavigator.setKeepParams(["type"])
    };
    return {
        init: init,
        format_trade_message: trade_message_format,
        format_system_message: system_message_format
    }
}();
var Feedback = function() {
    var feedback = {
        data: {},
        error_msg: "",
        show_error: function($item) {
            if ($item) {
                $item.addClass("i_Text_error")
            }
            $(".c_Red").text(this.error_msg)
        },
        clear_error: function($item) {
            $item.removeClass("i_Text_error")
        },
        get: function() {
            this.error_msg = "";
            var $email = $("input[name=email]");
            var email = $email.val().trim();
            if (email && !/^[\w-]+[\w._-]*@[\w-]+(\.[\w-]+)+$/.test(email)) {
                this.error_msg = i18n("please_input_the_correct_mailbox")
            }
            if (this.error_msg) {
                this.show_error($email);
                return
            }
            this.data["email"] = email;
            var $content = $("textarea[name=content]");
            var content = $content.val().trim();
            var CONTENT_MAX_LENGTH = 1024;
            if (!content) {
                this.error_msg = i18n("please_enter_the_question_content")
            } else if (content.length > CONTENT_MAX_LENGTH) {
                this.error_msg = i18n("content_length_can_not_be")
            }
            if (this.error_msg) {
                this.show_error($content);
                return
            }
            this.data["content"] = content;
            var img_url = $(".upload-pics .upload-item img").attr("src");
            if (img_url) {
                this.data["img_url"] = img_url
            }
            return true
        }
    };
    var submit_feedback = function() {
        if (feedback.get() == undefined) {
            return
        }
        $(".c_Red").text("");
        sendRequest("/api/feedback/add/v2", {
            data: feedback.data,
            method: "post",
            dataType: "json",
            success: function(data) {
                if (data.code != "OK") {
                    $(".c_Red").text(data.error);
                    return
                }
                Buff.toast(i18n("successfully_submitted"), {
                    type: "success"
                });
                location.reload()
            }
        })
    };
    var upload_image = function(e, fp) {
        var files = e.target.files;
        var file = files[0];
        options = {
            file: file,
            upload_url: fp.url,
            max_file_size: fp.max_size,
            token: fp.token,
            callback: function(data) {
                $(".upload-btn").hide();
                $(".upload-pics").show().find(".upload-item").html('<img src="' + data.url + '"/>');
                $(".upload-btn").next().html('<i class="icon icon_status_success"></i>' + i18n("successful_upload") + '<a href="javascript:;" class="f_12px f_Underline">' + i18n("reupload") + "</a>").find("a").click(function() {
                    $("#upload_file").click()
                })
            },
            onprogress: function(e) {
                if (e.lengthComputable) {
                    var percentVal = (e.loaded / e.total * 100).toFixed(2);
                    $(".upload-btn .upload-progressing").show();
                    $(".upload-btn").next().text(i18n("is_being_uploaded") + percentVal + "%")
                }
            }
        };
        uploadFile(options)
    };
    var init = function(fp) {
        $("#feedback_type,input[name=email],input[name=title],textarea[name=content]").bind("input change propertychange", function() {
            feedback.clear_error($(this))
        });
        $("#submit").click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            submit_feedback()
        });
        $("#upload_file").change(function(event) {
            upload_image(event, fp)
        })
    };
    return {
        init: init,
        upload_image: upload_image
    }
}();
var FeedbackList = function() {
    var get_feedback_logs = function(current_page, event) {
        if (current_page == undefined) {
            current_page = 1
        }
        sendRequest("/api/feedback/list/", {
            data: {
                page_num: current_page
            },
            method: "get",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    return
                }
                var feedbacks = data.data;
                if (feedbacks.has_unreplay) {
                    $(".Btn_to_submit").addClass("i_Btn_disabled").unbind().bind("click", function() {
                        Buff.toast(i18n("currently_have_to_wait_for"))
                    })
                } else {
                    $(".Btn_to_submit").removeClass("i_Btn_disabled").unbind().bind("click", function() {
                        Popup.show("j_popup_feedback")
                    })
                }
                $("#feedback_logs").show();
                $("#feedback_logs tr:not(:first)").remove();
                $("#feedback_logs tr").after(template_render("feedback_log_pat", {
                    feedbacks: feedbacks["items"]
                }));
                feedbacks.onPageClick = get_feedback_logs;
                renderPagination(feedbacks);
                $("#feedback_logs").delegate("td", "mouseover", function() {
                    $(this).css("cursor", "pointer")
                }).delegate("td", "click", function() {
                    var feedback_id = $(this).parent().attr("feedback_id");
                    location.href = "/user-center/feedback/detail/?id=" + feedback_id
                });
                if (feedbacks.announcement) {
                    $("#j_popup_feedback .popup-tip").html(feedbacks.announcement).show();
                    if (feedbacks.announcement_entry.url) {
                        $("#j_popup_feedback .popup-tip").bind("mouseover", function() {
                            $(this).css("cursor", "pointer")
                        }).bind("click", function() {
                            openPageOnNewTab(feedbacks.announcement_entry.url)
                        })
                    }
                } else {
                    $("#j_popup_feedback .popup-tip").html("").hide()
                }
            }
        })
    };
    var init = function(fp) {
        get_feedback_logs();
        Feedback.init(fp)
    };
    return {
        init: init
    }
}();
var FeedbackDetail = function() {
    var feedback_id;
    var get_detail = function() {
        sendRequest("/api/feedback/detail/", {
            data: {
                id: feedback_id
            },
            method: "get",
            dataType: "json",
            success: function(json_data) {
                if (json_data.code != "OK") {
                    return
                }
                var content = json_data.data.feedback.content;
                if (json_data.data.feedback.pictures) {
                    content += '<br><a href="' + json_data.data.feedback.pictures + '" target="_blank" ><img height="100" src="' + json_data.data.feedback.pictures + '"/></a>'
                }
                $(".text-cont").html(content);
                $(".list_tb:first").append(template_render("feedback_replay_pat", {
                    feedback_replays: json_data.data.feedback_replays
                }));
                if (json_data.data.can_replay) {
                    $(".feedback-form").show()
                } else {
                    $(".feedback-form").remove()
                }
            }
        })
    };
    var replay = {
        data: {},
        error_msg: "",
        get: function() {
            var content = $("textarea[name=content]").val().trim();
            if (!content) {
                this.error_msg = i18n("please_enter_the_question_content");
                return
            }
            var CONTENT_MAX_LENGTH = 1024;
            if (content.length > CONTENT_MAX_LENGTH) {
                this.error_msg = i18n("content_length_can_not_be");
                return
            }
            this.data["content"] = content;
            this.data["id"] = feedback_id;
            var img_url = $(".upload-pics .upload-item img").attr("src");
            if (img_url) {
                this.data["img_url"] = img_url
            }
            return true
        }
    };
    var enable_or_disable_submit = function() {
        if (replay.get() == undefined) {
            $("#submit").addClass("i_Btn_disabled").removeClass("i_Btn_main")
        } else {
            $("#submit").removeClass("i_Btn_disabled").addClass("i_Btn_main")
        }
    };
    var submit_replay = function() {
        if (replay.get() == undefined) {
            $(".c_Red").text(replay.error_msg);
            return
        }
        $(".c_Red").text("");
        sendRequest("/api/feedback/replay/", {
            data: replay.data,
            method: "post",
            dataType: "json",
            success: function(data) {
                if (data.code != "OK") {
                    $(".c_Red").text(data.error);
                    return
                }
                Buff.toast(i18n("reply_success"), {
                    type: "success"
                });
                location.reload()
            }
        })
    };
    var close = function() {
        Buff.alert({
            title: i18n("confirm"),
            message: i18n("whether_the_problem_has_been"),
            confirmText: i18n("ok"),
            success: function() {
                sendRequest("/api/feedback/close/", {
                    data: {
                        id: feedback_id
                    },
                    method: "post",
                    dataType: "json",
                    success: function(json_data) {
                        if (json_data.code != "OK") {
                            Buff.toast(i18n("close_failed_please_try_again"), {
                                type: "error"
                            })
                        }
                        location.reload()
                    }
                })
            }
        })
    };
    var init = function(fp) {
        feedback_id = getParams().id;
        if (!feedback_id) {
            return
        }
        get_detail();
        $("textarea[name=content]").bind("input change propertychange", enable_or_disable_submit);
        $("#submit").click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            submit_replay()
        });
        $("#close").click(function() {
            close()
        });
        $("#upload_file").change(function(event) {
            Feedback.upload_image(event, fp)
        })
    };
    return {
        init: init
    }
}();
var Flow = function() {
    var get_flow = function(current_page) {
        if (current_page == undefined) {
            current_page = 1
        }
        var data = {
            page_num: current_page
        };
        var log_category = $("#log_category").attr("value");
        var pay_category = $("#pay_category").attr("value");
        if (log_category) {
            data["log_category"] = log_category
        }
        data["pay_category"] = pay_category;
        sendRequest("/api/asset/flow/log/", {
            data: data,
            method: "get",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    alert(data.error);
                    return
                }
                var logs = data.data;
                $("#flow table tr:not(:first)").remove();
                if (logs.items.length == 0) {
                    $("#flow table").hide();
                    $("#flow .nodata").show()
                } else {
                    $("#flow .nodata").hide();
                    $("#flow table").append(template_render("flow_pat", {
                        flow: logs.items,
                        pay_category: pay_category
                    })).show()
                }
                logs.pager_name = "#flow .pager";
                logs.onPageClick = get_flow;
                renderPagination(logs)
            }
        })
    };
    var init = function() {
        $("#log_category").change(function() {
            get_flow()
        });
        $("#pay_category").change(function() {
            get_flow()
        });
        get_flow()
    };
    return {
        init: init
    }
}();
var Coupon = function() {
    var page_state;
    var get_coupon_list = function(current_page) {
        if (current_page == undefined) {
            current_page = 1
        }
        var data = {
            game: g.game,
            page_num: current_page,
            page_size: 12,
            state: page_state,
            only_coupon: 1
        };
        sendRequest("/api/activity/coupon/my/", {
            data: data,
            method: "get",
            dataType: "json",
            showLoading: false,
            success: function(data) {
                if (data.code != "OK") {
                    return
                }
                var coupons = data.data;
                if (coupons["items"].length == 0) {
                    $(".nodata").show()
                } else {
                    var items = coupons["items"];
                    for (var i = 0; i < items.length; i++) {
                        var description = items[i].description;
                        if (description) {
                            description = description.replace(/·/g, "").trim().split("\n")
                        } else {
                            description = []
                        }
                        items[i].description = description;
                        if (page_state == "used") {
                            items[i].tab_class = "user-coupon-gray"
                        }
                    }
                    var $list_tb = $(".user-coupon-list");
                    $list_tb.empty();
                    $list_tb.append(template_render("coupon_detail_pat", {
                        coupons: items
                    }));
                    $list_tb.show()
                }
                coupons.onPageClick = get_coupon_list;
                renderPagination(coupons)
            },
            error: function() {}
        })
    };
    var init = function(state) {
        page_state = state;
        get_coupon_list();
        $("#exchange_key").click(function() {
            var cdkey = $("input[name=cdkey]").val();
            if (!cdkey) {
                Buff.toast(i18n("please_enter_the_redemption_code"), {
                    type: "error"
                });
                return
            }
            var data = {
                cdkey: cdkey
            };
            sendRequest("/api/activity/cdkey/exchange/", {
                data: data,
                method: "post",
                dataType: "json",
                showLoading: false,
                success: function(data) {
                    if (data.code != "OK") {
                        Buff.toast(data.error, {
                            type: "error"
                        });
                        return
                    }
                    Buff.toast(data.data.message, {
                        type: "success"
                    });
                    setTimeout(function() {
                        location.reload()
                    }, 3e3)
                }
            })
        })
    };
    return {
        init: init
    }
}();
var GiftCard = function() {
    var receiverInfo = {};
    var showReceiverInfo = function() {
        var $item = $("#receiver_info");
        var nickname = $("input[name=nickname]").val().trim();
        if (nickname == receiverInfo["nickname"]) {
            return
        }
        receiverInfo = {};
        $item.hide();
        enableOrDisableButton();
        if (!nickname) {
            return
        }
        sendRequest("/api/activity/gift_card/receiver_info/", {
            method: "get",
            data: {
                nickname: nickname
            },
            success: function(json_data) {
                if (json_data.code != "OK") {
                    Buff.toast(json_data.error);
                    return
                }
                receiverInfo = json_data.data;
                if (receiverInfo.id) {
                    var $body = $("<div></div>");
                    $body.append(i18n("gift_card_receiver_info"));
                    $body.append('&nbsp;<img width="26" height="26" src="' + receiverInfo.avatar + '">&nbsp;');
                    $body.append('<a href="/shop/' + receiverInfo.id + '" target="_blank"><strong>' + receiverInfo.nickname + "</strong></a>");
                    $item.html($body.html());
                    $item.show();
                    enableOrDisableButton()
                } else {
                    Buff.toast(i18n("gift_card_receiver_nickname_error"))
                }
            }
        })
    };
    var getData = function() {
        var amount = $("#amount_list").attr("value");
        if (amount) {
            amount = parseInt(amount)
        }
        var receiver_nickname = $("input[name=nickname]").val();
        var receiver_id = receiverInfo.id;
        return {
            amount: amount,
            receiver_nickname: receiver_nickname,
            receiver_id: receiver_id
        }
    };
    var enableOrDisableButton = function() {
        var data = getData();
        var $button = $("#confirm_buy");
        if (data["amount"] && data["receiver_nickname"] && data["receiver_id"]) {
            $button.removeClass("i_Btn_disabled")
        } else {
            $button.addClass("i_Btn_disabled")
        }
    };
    var showServiceFee = function() {
        var data = getData();
        sendRequest("/api/activity/gift_card/fee/", {
            method: "get",
            data: data,
            success: function(json_data) {
                if (json_data.code != "OK") {
                    Buff.toast(json_data.error);
                    return
                }
                var tips = [receiverInfo["nickname"], json_data.data["amount"], json_data.data["fee"], json_data.data["real_amount"]];
                $("#j_gift_card_buy_confirm .popup-desc strong").each(function(index) {
                    $(this).text(tips[index])
                });
                Popup.hide();
                Popup.show("j_gift_card_buy_confirm")
            }
        })
    };
    var showAuthcode = function(mobile) {
        var manager = commonAuthcodeVerifyManager(mobile, "/api/activity/gift_card/send_authcode/", null, "/api/activity/gift_card/buy/", getData(), function(resp) {
            Buff.alert({
                title: i18n("buy_success"),
                message: i18n("gift_card_buy_success", {
                    nickname: receiverInfo["nickname"],
                    sn: resp.sn
                }),
                hideCancel: true,
                confirmText: i18n("ok"),
                success: function() {
                    window.location.reload()
                }
            })
        });
        manager.init()
    };
    var buy = function() {
        var data = getData();
        sendRequest("/api/activity/gift_card/buy/", {
            method: "post",
            data: data,
            success: function(json_data) {
                if (json_data.code != "OK") {
                    Buff.toast(json_data.error);
                    return
                }
            }
        })
    };
    var init = function(mobile) {
        $("#amount_list").bind("change", function() {
            enableOrDisableButton()
        });
        $("input[name=nickname]").change(function(event) {
            showReceiverInfo()
        });
        $("#confirm_buy").click(function() {
            if ($(this).hasClass("i_Btn_disabled")) {
                return
            }
            showServiceFee()
        });
        $("#j_gift_card_buy_confirm .i_Btn_main").click(function() {
            showAuthcode(mobile)
        })
    };
    return {
        init: init
    }
}();
var Premium = function() {
    var pay_data = {};
    var init = function() {};
    var show_expired_popup = function(user_id, expired_date, expired_date_format) {};
    var premium_pay = function() {
        sendRequest("/account/api/premium_buy", {
            data: pay_data,
            dataType: "json",
            method: "POST",
            success: function(data) {
                if (data.code != "OK") {
                    var error_msg = data.error || i18n("premium_buy_fail");
                    Buff.toast(error_msg, {
                        type: "warning"
                    });
                    return
                }
                var popup_closed_callback = function() {
                    Buff.alert({
                        title: i18n("premium_waiting_for_payment"),
                        message: i18n("premium_havent_successfully_paid"),
                        confirmText: i18n("premium_continue_to_pay"),
                        cancelText: i18n("premium_confirm_leave"),
                        success: function() {
                            Popup.show("j_popup_wx")
                        },
                        cancel: function() {
                            window.location.reload()
                        },
                        onClose: function() {
                            window.location.reload()
                        }
                    })
                };
                var wait_second = 5;
                if (pay_data.pay_method == BuffConfig.PayMethod.WX_PAGE) {
                    var pay_params = data.data.pay_params;
                    wait_second = pay_params.pay_expire_timeout;
                    wxPayShowQrcode(pay_data.price, pay_params.url, wait_second, popup_closed_callback)
                } else if (pay_data.pay_method == BuffConfig.PayMethod.ALIPAY_PAGE) {
                    var pay_params = data.data.pay_params;
                    location.href = pay_params.url
                } else {
                    $("#loading-cover").show()
                }
                check_after_pay(data.data.order_id, pay_data.pay_method, wait_second, true)
            },
            error: function(resp) {
                $("#loading-cover").hide();
                Popup.hide();
                Buff.alert({
                    title: i18n("prompt"),
                    message: i18n("the_system_is_busy_please"),
                    hideCancel: true
                })
            }
        })
    };
    var check_after_pay = function(order_id, pay_method, wait_second, reload) {
        var _query_order = function(order_id, dtd) {
            sendRequest("/account/api/premium_record", {
                data: {
                    order_id: order_id
                },
                dataType: "json",
                showLoading: false,
                method: "GET",
                success: function(data) {
                    dtd.notify();
                    if (data.code != "OK") {
                        return
                    }
                    if (data.data.items.length != 1) {
                        return
                    }
                    order = data.data.items[0];
                    if (order.state == "PAY_SUCCESS") {
                        Buff.toast(i18n("premium_buy_success"), {
                            type: "success"
                        });
                        dtd.resolve();
                        if (reload) {
                            setTimeout(function() {
                                window.location.reload()
                            }, 500)
                        }
                    } else if (order.state == "PAY_FAILED") {
                        dtd.reject()
                    }
                }
            })
        };
        payWaitResult(order_id, pay_method, wait_second, _query_order)
    };
    var join_plus = function() {
        sendRequest("/account/api/premium_package", {
            data: {},
            dataType: "json",
            method: "GET",
            success: function(data) {
                if (data.code != "OK") {
                    Buff.toast(data.error, {
                        type: "warning"
                    });
                    return
                }
                Popup.hide();
                var pay_methods = data.data.pay_methods;
                var premium_package = data.data.packages;
                var pay_content = template_render("pay_content_premium", {
                    premium_package: premium_package
                });
                var default_premium_package = premium_package[0];
                var payMethod = payMethodPopup();
                payMethod.show({
                    pay_methods: data.data.pay_methods,
                    price: default_premium_package.discount_price,
                    pay_content: pay_content,
                    onPaymethodChange: function(value) {
                        pay_data.pay_method = value
                    },
                    onPayContentChange: function(package_id, price) {
                        pay_data.package_id = package_id;
                        pay_data.price = price
                    },
                    onConfirm: function() {
                        premium_pay()
                    }
                })
            }
        })
    };
    return {
        init: init,
        join_plus: join_plus,
        show_expired_popup: show_expired_popup,
        check_after_pay: check_after_pay
    }
}();
var createRollRoom = function(max_items_count) {
    var backpackItems = [];
    var selectedItems = [];
    var goods_infos = {};
    var createData = {};
    var RollRoomType = {
        NORMAL: 0,
        PASSWORD: 1
    };
    var max_items_count = max_items_count || 100;
    var search = "";
    function isURL(str) {
        var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
        if (!regex.test(str)) {
            return false
        } else {
            return true
        }
    }
    var selectedItemsCount = function() {
        var count = 0;
        for (var i = 0; i < backpackItems.length; i++) {
            if (backpackItems[i].selected == true) {
                count += 1
            }
        }
        return count
    };
    var renderPool = function() {
        var count = 0;
        var total_price = 0;
        for (var i = 0; i < backpackItems.length; i++) {
            if (backpackItems[i].selected == true) {
                total_price += parseFloat(goods_infos[backpackItems[i].goods_id].steam_price_cny);
                count += 1
            }
        }
        $("#reward_count").text(count + "/" + max_items_count);
        $(".input-hud").text("≤" + count);
        $("#total_price").text("￥" + total_price.toFixed(2));
        var html = template_render("prize_pool_pat", {
            count: count,
            items: backpackItems,
            goods_infos: goods_infos
        });
        $(".prize_pool .switch_box").html(html)
    };
    var renderBackpack = function() {
        var count = 0;
        for (var i = 0; i < backpackItems.length; i++) {
            if (backpackItems[i].selected != true)
                count += 1
        }
        var html = template_render("buff_backpack_pat", {
            count: count,
            items: backpackItems,
            goods_infos: goods_infos,
            search: search.toLocaleLowerCase()
        });
        $(".buff_backpack .switch_box").html(html)
    };
    var showInfo = function() {
        $(".step_tab").removeClass("active");
        $(".step_tab.info").addClass("active");
        $("#tab_info").show();
        $("#tab_pool").hide()
    };
    var showPool = function() {
        $(".step_tab").removeClass("active");
        $(".step_tab.pool").addClass("active");
        $("#tab_info").hide();
        $("#tab_pool").show()
    };
    var checkStep1Data = function() {
        var name = $('input[name="name"]').val().trim();
        if (name.length < 1) {
            Buff.toast("请填写活动名称");
            $('input[name="name"]').addClass("i_Text_error");
            return false
        } else if (name.length > 12) {
            Buff.toast("活动名称不能超过12个字");
            $('input[name="name"]').addClass("i_Text_error");
            return false
        }
        var brief = $('textarea[name="brief"]').val().trim();
        if (brief.length < 5) {
            Buff.toast("活动介绍不小于5个字");
            $('textarea[name="brief"]').addClass("i_Text_error");
            return false
        } else if (brief.length > 200) {
            Buff.toast("活动介绍不超过200个字");
            $('textarea[name="brief"]').addClass("i_Text_error");
            return false
        }
        var date = $('.w-Select[name="date"]').attr("value");
        if (typeof date == "undefined" || date.length < 1) {
            Buff.toast("请选择开奖日期");
            $('.w-Select[name="date"]').addClass("i_Text_error");
            return false
        }
        var hours = $('input[name="hours"]').val();
        var minutes = $('input[name="minutes"]').val();
        if (hours == "小时") {
            Buff.toast("请选择开奖时间");
            $('input[name="hours"]').addClass("i_Text_error");
            return false
        }
        if (minutes == "分钟") {
            Buff.toast("请选择开奖时间");
            $('input[name="minutes"]').addClass("i_Text_error");
            return false
        }
        var draw_time = date + " " + hours + ":" + minutes + ":00";
        if (moment(draw_time, "YYYY-MM-DD hh:mm:ss") - moment().add(10, "minutes") < 0) {
            Buff.toast("开奖时间必须晚于10分钟之后");
            $('input[name="hours"]').addClass("i_Text_error");
            $('input[name="minutes"]').addClass("i_Text_error");
            return false
        }
        var type = $('.w-Select[name="type"]').attr("value");
        if (typeof type == "undefined") {
            Buff.toast("请选择活动类型");
            $('.w-Select[name="type"]').addClass("i_Text_error");
            return false
        }
        var password = $('input[name="password"]').val();
        if (type == RollRoomType.PASSWORD) {
            if (password.length < 4) {
                Buff.toast("请输入大于4位的密码");
                $('input[name="password"]').addClass("i_Text_error");
                return false
            } else if (password.length > 24) {
                Buff.toast("请输入小于24位的密码");
                $('input[name="password"]').addClass("i_Text_error");
                return false
            }
            createData.password = password
        } else {
            delete createData.password
        }
        var intro_name = $('input[name="intro_name"]').val();
        if (intro_name.length > 24) {
            Buff.toast("链接文本不能超过24个字");
            $('input[name="intro_name"]').addClass("i_Text_error");
            return false
        } else if (intro_name.length > 0 && intro_name.length < 2) {
            Buff.toast("链接文本不能少于2个字");
            $('input[name="intro_name"]').addClass("i_Text_error");
            return false
        }
        var intro_url = $('input[name="intro_url"]').val();
        if (intro_url.length > 0 && isURL(intro_url) == false) {
            Buff.toast("请输入正确的链接");
            $('input[name="intro_url"]').addClass("i_Text_error");
            return false
        }
        if (intro_url.length > 0 && intro_name.length < 1) {
            Buff.toast("请输入链接文字");
            $('input[name="intro_name"]').addClass("i_Text_error");
            return false
        }
        if (intro_name.length > 0 && intro_url < 1) {
            Buff.toast("请输入链接地址");
            $('input[name="intro_url"]').addClass("i_Text_error");
            return false
        }
        createData.appid = $('.w-Select[name="appid"]').attr("value");
        createData.name = name;
        createData.brief = brief;
        createData.draw_time = draw_time;
        createData.type = type;
        if (intro_name.length > 0) {
            createData.intro_name = intro_name
        } else {
            delete createData.intro_name
        }
        if (intro_url.length > 0) {
            createData.intro_url = intro_url
        } else {
            delete createData.intro_url
        }
        return true
    };
    var checkStep2Data = function() {
        var count = 0;
        var backpack_ids = [];
        for (var i = 0; i < backpackItems.length; i++) {
            if (backpackItems[i].selected == true) {
                backpack_ids.push(backpackItems[i].id);
                count += 1
            }
        }
        if (count < 1) {
            Buff.toast("请选择至少一件饰品");
            return false
        }
        var reward_count = parseInt($('input[name="reward_count"]').val());
        if (isNaN(reward_count) || reward_count < 1) {
            Buff.toast("请输入获奖人数");
            $('input[name="reward_count"]').addClass("i_Text_error");
            return false
        } else if (reward_count > count) {
            Buff.toast("可获奖人数需小于等于奖池饰品数量");
            $('input[name="reward_count"]').addClass("i_Text_error");
            return false
        }
        createData.reward_count = reward_count;
        createData.backpack_ids = backpack_ids.join(",");
        return true
    };
    var refresh_backpack = function() {
        sendRequest("/api/market/backpack", {
            data: {
                appid: createData.appid,
                page_size: 1e3
            },
            showLoading: false,
            method: "GET",
            success: function(data) {
                goods_infos = data.data.goods_infos;
                var selected_assetids = [];
                for (var i = 0; i < backpackItems.length; i++) {
                    if (backpackItems[i].selected == true) {
                        selected_assetids.push(backpackItems[i].asset_info.assetid)
                    }
                }
                backpackItems = [];
                for (var i = 0; i < data.data.items.length; i++) {
                    var assetid = data.data.items[i].asset_info.assetid;
                    if (selected_assetids.indexOf(assetid) > -1) {
                        data.data.items[i].selected = true
                    }
                }
                backpackItems = data.data.items;
                renderBackpack();
                renderPool()
            }
        })
    };
    var init = function() {
        $("body").on("focus", ".timepicker input", function() {
            if ($(this).parent().hasClass("disabled")) {
                $(this).blur();
                return false
            } else {
                var index = $(".timepicker input").index(this);
                $(".timepicker-drop").eq(index).show()
            }
        }).on("blur", ".timepicker input", function() {
            $(this).removeClass("i_Text_error");
            $('input[name="hours"]').removeClass("i_Text_error");
            $('input[name="minutes"]').removeClass("i_Text_error");
            var _this = this;
            setTimeout(function() {
                var index = $(".timepicker input").index(_this);
                $(".timepicker-drop").eq(index).hide()
            }, 200)
        }).on("keypress", ".timepicker input", function() {
            return false
        }).on("keypress", "input[name='reward_count']", function() {
            var code = event.keyCode || event.charCode;
            var realkey = String.fromCharCode(code);
            return /\d/.test(realkey)
        }).on("click", ".timepicker-drop li", function() {
            $(this).addClass("on").siblings().removeClass("on");
            var inputID = $(this).parent().attr("data-for");
            $("#" + inputID).val($(this).html())
        }).on("change", '.w-Select[name="type"]', function() {
            var type = $(this).attr("value");
            if (type == RollRoomType.PASSWORD) {
                $("#row_password").show()
            } else {
                $("#row_password").hide()
            }
        }).on("click", ".buff_backpack .switch_box .item-card", function() {
            tooltip.abortLast();
            var index = $(this).data("index");
            var count = 0;
            for (var i = 0; i < backpackItems.length; i++) {
                if (backpackItems[i].selected == true)
                    count += 1
            }
            if (count >= max_items_count) {
                Buff.toast("超过最大可添加件数");
                return
            }
            backpackItems[index].selected = true;
            selectedItems.push(backpackItems[index]);
            renderBackpack();
            renderPool()
        }).on("click", ".prize_pool .switch_box .item-card", function() {
            tooltip.abortLast();
            var index = $(this).data("index");
            backpackItems[index].selected = false;
            renderBackpack();
            renderPool()
        }).on("change", '.w-Select[name="appid"]', function() {
            var appid = $(this).attr("value");
            if (typeof createData.appid != "undefined" && createData.appid != appid && selectedItemsCount() > 0) {
                Buff.alert({
                    title: "切换游戏",
                    message: "切换游戏后，将清除已添加的奖池信息，你可以从“我的背包”中添加物品。",
                    type: "error",
                    confirmText: "确定切换",
                    success: function() {
                        createData.appid = appid;
                        backpackItems = []
                    },
                    cancel: function() {
                        Buff.setCompValue("app-select", createData.appid)
                    },
                    onClose: function() {
                        Buff.setCompValue("app-select", createData.appid)
                    }
                })
            }
        }).on("blur", "#search", function() {
            if (search.length < 1) {
                $("#search-area").hide();
                $("#btn-search").show()
            }
        }).on("input", "#search", function() {
            search = $(this).val();
            renderBackpack()
        }).on("change", "input,textarea,.w-Select", function() {
            $(this).removeClass("i_Text_error")
        }).on("click", "#go_steam_inventory", function() {
            window.open("/market/steam_inventory?game=" + BuffConfig.SteamAPP.APPID_MAPS[createData.appid])
        });
        $("#refresh_backpack").click(function() {
            refresh_backpack()
        });
        $(".step_tab.info").click(function() {
            showInfo()
        });
        $(".step_tab.pool").click(function() {
            if (checkStep1Data()) {
                showPool();
                refresh_backpack()
            }
        });
        $("#set_pool").click(function() {
            if (checkStep1Data()) {
                showPool();
                refresh_backpack()
            }
        });
        $("#publish_room").click(function() {
            if (checkStep2Data()) {
                Buff.alert({
                    title: "创建免费饰品活动",
                    message: "免费饰品活动创建后不能取消，请确认是否创建。",
                    success: function() {
                        sendRequest("/api/roll/room/create", {
                            method: "POST",
                            data: createData,
                            success: function(data) {
                                if (data.code != "OK") {
                                    Buff.toast(data.error)
                                } else {
                                    window.location.href = "/roll/room/" + data.data.id
                                }
                            }
                        })
                    },
                    confirmText: "确认创建",
                    cancelText: "取消创建"
                })
            }
        });
        $("#set_info").click(function() {
            showInfo()
        });
        $("#btn-search").click(function() {
            $(this).hide();
            $("#search-area").css({
                display: "inline-block"
            })
        })
    };
    return {
        init: init
    }
};
$(function() {
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        if (typeof WebViewInfo != "undefined" && WebViewInfo.webview_from)
            return;
        if (getCookie("webview_from"))
            return;
        var cont = '<div id="app-download-bar" style="">' + '<img src="/static/images/app_logo.jpg" class="app-logo">' + "<h3>" + i18n("platform_name") + "</h3>" + "<h5>" + i18n("slogan") + "</h5>" + '<a class="download-btn" href="https://adl.netease.com/d/g/buff/c/gw">' + i18n("download") + "</a>" + "</div>";
        $("body").prepend(cont);
        var paddingTop = parseInt($("body").css("padding-top")) || $("#app-download-bar").height();
        $("body").css({
            "padding-top": paddingTop
        })
    }
});
